Tuesday, January 30, 2018

How To: Schedule Cron Job using python-crontab

We have already learnt how to schedule cron job manually. Now we will schedule cron job using python code.

Create an empty python file with .py entension.

Paste following code step by step:

# Create CronTab instance.
cron = CronTab(user=True) 


# Remove all previous jobs having comment id 'My_Job'
cron.remove_all(comment='My_Job')


# Schedule new job having comment id 'My_Job'
job = cron.new(comment='My_Job', command='/usr/bin/python3 /home/root/Schedular/scheduleCronJob.py >> /home/root/Schedular/Logs.txt')

# Set timeslot to run this job
job.setall(str(timeSlot))

# Write to file.
cron.write()



This is all, save file and run/execute this python file.

Install following required packages before execution of file.

pip3 install python-crontab
pip3 install schedule


If you have also installed crontab package then you may see some errors, to uninstall crontab use following command:

pip3 uninstall crontab


Upon successful execution, this will schedule a new cron job in ubuntu.

To list existing cron jobs enter following command in terminal window:

crontab –l


Click here for complete code.

How To: Schedule Cron Job in Ubuntu

Open a Terminal Window (Command Line) in ubuntu.
Type following command and press Enter.


 crontab -e


This will open editor for you. Write cron command at the end of file.

Use sudo if root privileges required. e.g


 sudo crontab -e


Use following pattern to create new cron job syntax:
  1. The number of minutes after the hour (0 to 59) 
  2. The hour in military time (24 hour) format (0 to 23) 
  3. The day of the month (1 to 31) 
  4. The month (1 to 12) 
  5. The day of the week (0 or 7 is Sun, or use name) 
  6. The command to run 

For example


 0 7 * * * /path/to/your/script.sh


This syntax will run script.sh at 7:00 AM daily.

File must have executable permissions. Run following command to make file executable.


  chmod +x /path/to/your/script.sh


If you want to schedule python file to run via cron, use following command instead.


  0 7 * * * /usr/bin/python3 /path/to/your/pythron-file.py


Just make sure you have already installed python3.

To list existing cron jobs enter following command:


 crontab -l


To remove an existing cron job enter following command:


 crontab -e


Delete the line that contains your cron job and save file.