Antony's Blog

Let Cron do the Job.

June 01, 2020

How to set up Cron job in Linux

Everybody forgets to run a script sometime, but how to schedule these tasks, this is where cron is a big help ✌.

“The software utility Cron is a time-based job scheduler in Unix-like computer operating systems. Users that set up and maintain software environments use cron to schedule jobs (commands or shell scripts) to run periodically at fixed times, dates, or intervals.” - Wikipedia

which is exactly which we need, but how to set up ?
if you are running on a Linux machine you are in luck, it’s already installed.👊

sudo service cron start
sudo service cron status

to start cron and to get status, but to get user-specific crontab use:

crontab -e

this will show diffrent editor options to choose from,choose the nano version, as it’s the most simplest. then follow this format

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7)
# |  |  |  |  |
# *  *  *  *  *   command to be executed

for example:

MAILTO=antonyjm462@gmail.com
SHELL=/bin/bash
PATH=/bin:/usr/bin:/my/path/bin
DISPLAY=:0
XAUTHORITY=/home/antony/.Xauthority
40 22 * * * . /etc/profile; /home/antony/Code/Telegram/job.sh >> /home/antony/Code/Telegram/cron.log 2>&1

Ya I know, for automation of udemy script 🙈. you can also define the path var inside the crontab also with other variables for the script to work.
to create a cron job for more info on formatting use guru but you can’t use normal env variables inside cron. but don’t be dishearted there is a way.
Embed the file inside job.sh which contains the script 👉

#!/bin/sh
/usr/bin/python3 /home/antony/Code/Telegram/telegram.py

Always put the full path, because cron don’t get hold of the path and environ variables. And don’t forget to give all the files executable permission

chmod +x job.sh
chmod +x filename.ext

If problems arise :

  1. Make sure the script in /etc/cron.d/ is owned by root:root chmod root:root /etc/cron.d/script
  2. Make sure the script ends with a newline
  3. If the script seem to not work try with a simples one e.g. * * * * * root echo test >> /tmp/* cron_temp and monitor /tmp/cron_temp
  4. service cron status will provide hints of how well the line executed
  5. If the lines executed seems to be the culprit try running it as the user in the cron file sudo -u username command-to-be-run


    always use sudo -u username command-to-be-run before you finish the process
    All done, Sit back and enjoy.✌