Skip to content

Cron jobs and Docker

BK Jackson edited this page Sep 10, 2021 · 4 revisions

Cron jobs and docker

Stackoverflow - How to run a cron job inside a docker container
github docker-cron - docker cron example on github
Running a Cron Job in Docker Container - Knoldus blog

Running python from a shell script

Excusting a python program from a shell script

helpful cron sites

crontab guru - easy way to test cron schedule expressions
cronitor - cron job monitoring service

cron command format

minute hour day month weekday  <command-to-execute>

Schedule a job to run every minute

* * * * * command  

Schedule a job to run every hour while you're working (9am-5 pm, Mon-Fri)

0 9-17 * * 1-5 command  

Run a job every two hours

0 */2 * * * command  

Make sure cron is working with log files

* * * * * echo "test" >> logfile 2>&1

Configure to send emails with the output of cron jobs

Cron can be configured to send emails with the output of jobs. It actually does this by default with your user account’s default email address, but it likely isn’t configured properly. To get email working, you’ll need a mail agent set up and configured on your server, which will allow you to use the mail command to send emails. Then, place this line above your cron jobs in your cron job:

MAILTO="yourname@gmail.com"

Disable a cron job quickly in crontab

0 0 1 * * this_job_i_want.sh

# uncomment below to enable
# 0 0 2 * * this_job_i_dont_want.sh

Schedule a job to clear temporary files every midnight

echo "0 0 * * * rm -f /tmp/deepak/*" >> /var/spool/cron/deepak

Validate the cron job content

Use -u to define the username for which you wish to perform the cron action

crontab -u deepak -l

Bash shell script to create cron job that removes files every night at midnight

#!/bin/bash
   if [ `id -u` -ne 0 ]; then
      echo "This script can be executed only as root, Exiting.."
      exit 1
   fi

case "$1" in
   install|update)

	CRON_FILE="/var/spool/cron/root"

	if [ ! -f $CRON_FILE ]; then
	   echo "cron file for root doesnot exist, creating.."
	   touch $CRON_FILE
	   /usr/bin/crontab $CRON_FILE
	fi

	# Method 1
	grep -qi "cleanup_script" $CRON_FILE
	if [ $? != 0 ]; then
	   echo "Updating cron job for cleaning temporary files"
           /bin/echo "0 0 * * * rm -f /home/deepak/cleanup_script.sh" >> $CRON_FILE
	fi

	# Method 2
	grep -qi "cleanup_script" $CRON_FILE
	if [ $? != 0 ]; then
	   echo "Updating cron job for cleaning temporary files"
	   crontab -u deepak -l >/tmp/crontab
           /bin/echo "0 0 * * * rm -f /home/deepak/cleanup_script.sh" >> /tmp/crontab
	   crontab -u deepak /tmp/crontab
	fi

	;;
	
	*)
	
	echo "Usage: $0 {install|update}"
	exit 1
    ;;

esac  

Articles

What is a Cron Job, and How Do You Use Them?

Clone this wiki locally