In Unix/Linux world, crontab is very useful tool to schedule any job/script to trigger on particular time. There are so many tools out there in the market as scheduling tools that follow the concepts of crontab.
So I would start running you through writing simple crontab application using python, that can promote you developing your own simple application as the start in python language.
Before we start writing crontab application in python, I wanted to give you requirements that implemented in crontab.
Cron is a system daemon used to execute desired tasks (in the background) at designated times.
A crontab file is a simple text file containing a list of commands meant to be run at specified times. It is edited using the crontab command. The commands in the crontab file (and their run times) are checked by the cron daemon, which executes them in the system background.
Each user (including root) has a crontab file. The cron daemon checks a user’s crontab file regardless of whether the user is actually logged into the system or not and trigger the respective script/jobs based on the scheduled time.
How to schedule the job using crontab? to schedule any job using crontab, first, we need to edit the crontab table file by executing the command as below,
vinoth@LAPTOP-U4G2071G:~$ crontab -e
which will get you to the table file where you have to mention time in the format of minute (0-59), hour (0-23, 0 = midnight), day (1-31), month (1-12), weekday (0-6, 0 = Sunday) followed by the script/job with complete path that you wanted to call.
Having this in my mind, I have written simple python code as my first learning steps for python programming language.
The crontab is available under https://github.com/Vino-git/Learninone/blob/master/Cron-Job.py
Now let’s walk through on the code.
The requirements for our program is scheduler. So obviously, time module is important. Hence I have imported time modules.
def cron_time(minu, hour, day_of_month, month_of_year, day_of_week, year):
In any language, writing your piece of code as a function would always meaningful. Refer https://docs.python.org/2/tutorial/controlflow.html#defining-functions
If you would have noticed, the syntax “:” refers the definition of a new block. When I start writing the code as per requirements, I need to pass 6 parameters same as we pass to crontab file such as minute, hour, day_of_month, month_of_year, day_of_week, year for the program to refer and return a true boolean value.
try: -------------- set of codes-------- --------------- except:
During lexical analysis happen in my code, there are chances that it may get aborted due to some kind of runtime error.
Note: In python, when we execute the code. The python compiler performs translation of source code into bytes code. During this translation, the compiler performs syntax analysis, lexical analysis, etc.
In order to catch that runtime error and proceed my code to end on the smooth way, I use to try & except keyword. When the python parser, read the keyword “Try:” it will go and check whether “except:” present in my code block. Further, the parser carefully walks through the code and if any error found in the code then it will directly go to except block and do whatever we ask the parser to do. Say, I ask the parser to continue or exit based on the severity of error that raised in the try block.
As next steps, I get the present time of my system time as below.
>>> localtime = time.localtime() >>> print localtime time.struct_time(tm_year=2017, tm_mon=10, tm_mday=16, tm_hour=22, tm_min=23, tm_sec=33, tm_wday=0, tm_yday=289, tm_isdst=0)
Here the time module has thrown me the output of current time details from seconds till year with daylight saving indicator. The daylight saving will have non-zero values if my system set with DSL.
Next, I simply do nested if conditions by referring localtime.tm_min is greater or equal to given minutes in the parameter and I follow the same concept till a year. If the given parameters are lesser than the current system minutes, hour, day, month, week & year then the program will return the boolean value “True” else return “false”
In the above example, we are doing the scheduler verification but we need the daemon to keep running this cron_time. In order to create daemon process using python, I have used the scheduler, threading & time modules.
As usual, to write daemon program we need to import above-said modules,
import sched --Scheduler to schedule the job/script import time -- import os from threading import Timer s=sched.scheduler(time.time,time.sleep)
Scheduler in the submodule of sched for which we can pass the objects of time.time (to get current seconds) and time.sleep (to set the intervals to invoke for scheduler). Please go through this link https://docs.python.org/2/library/sched.html?highlight=sched
while True: time_next=10 if cron_time(30,'*','*','*','*','*'): s.enter(time_next,1,"job/script") time.sleep(5)
I have created an indefinite1 loop which validates the cron_time trigger and sleeps for 5 seconds.
Now let’s see how the cron_time working on my window computer.
>>> while True: time_next=1 if cron_time('*','*','*','*','*','*'): s.enter(time_next,1,simpl_print(),()) time.sleep(59) Wow, I have got cron like scheduler on my windows Wow, I have got cron like scheduler on my windows Wow, I have got cron like scheduler on my windows
- I have executed the cron_time function in my python IDLE console.
- Created simple function called simpl_print()
- imported necessary modules for scheduling my task and called my simpl_print() function using the scheduler to print every minute.
Hope you should have some understanding or confident about how python code can be written. I encourage you to practice with your own small requirements as a project.