Cron is a popular tool to schedule tasks, it comes pre-installed on almost any Linux image such as Debian or Ubuntu. Cron can execute any command at a predefined time like 4:30 AM or every 2 minutes. For this reason, it is the first choice of developers for scheduled script execution.
¶ Example with Code
docker-compose to start and stop the docker container.
Here’s my docker compose file:
version: "3.1" services: price-daemon: image: node:14-alpine working_dir: /home/node/app volumes: - ./:/home/node/app command: "/usr/sbin/crond -f -l 0 -c /home/node/app/crontab -L /var/log/cron.log"
I use the lightweight
node:14-alpine image and mount my current working directory as volume.
command starts the cron daemon and it will look for the file
-l 0 if you don’t like a super verbose log. In my working directory I created the file
crontab/root with this contents:
# min hour day month weekday command * * * * * /bin/date --rfc-2822 >> /var/log/cron.log */30 * * * * node /home/node/app/scheduled.js >> /var/log/cron.log 2>&1
The second line is just a timestamp printed into the log file for debugging purposes. The third line executes the
scheduled.js file and logs its output into
And that’s it. Pretty simple right?