Cron is a Unix-like operating system software utility that allows us to schedule tasks. Cron’s tasks are specified in a Crontab, which is a text file that contains the instructions to run. The Crontab module in Python allows us to handle scheduled operations using Cron. It has functionalities that allow us to access Cron, create jobs, establish limitations, and remove jobs, among other things. In this article, we will perform Multiple jobs using Python-Crontab.
Let’s get started.
Installing Python-Crontab
First, we will need to make sure that we have python-crontab installed in your system. We can do so by typing the following command:
pip3 install python-crontab
Getting access to Crontab
We can get access to a crontab in five ways, three of which are system techniques that only operate on Unix-based operating systems and require the necessary permissions:
from crontab import CronTab empty_cron = CronTab() my_user_cron = CronTab(user=True) users_cron = CronTab(user='username')
There are other two non-system methods that will work on Windows:
file_cron = CronTab(tabfile='filename.tab') mem_cron = CronTab(tab=""" * * * * * command""")
Creating a New Job
We may use the following command to create a new cron job after we’ve accessed cron:
cron.new(command="cron_command")
For example, to create a cron job to run a python file temp.py every minute, we can do so by typing the below code:
from crontab import CronTab cron = CronTab(user='root') job = cron.new(command='python temp.py') job.minute.every(1) cron.write()
Creating Multiple jobs
Now let’s use the above knowledge to create multiple jobs and run them simultaneously. For the purposes of demonstration, We have created 2 python files, namely test1.py and test2.py, which are used to log their access times on a file called test.txt
The following is the content of the python files
test1.py:
Python3
from datetime import datetime import os cwd = os.getcwd() with open (os.path.join(cwd, "test.txt" ), "a" ) as f: f.write( "Accessed test1.py on " + str (datetime.now()) + "\n" ) |
test2.py:
Python3
from datetime import datetime import os cwd = os.getcwd() with open (os.path.join(cwd, "test.txt" ), "a" ) as f: f.write( "Accessed test2.py on " + str (datetime.now()) + "\n" ) |
Now, We have created a file that is used to create cron-jobs whose main purpose is to run these python files at an interval of 2 minutes and 1 minute respectively. The following is the content of the python file.
Python3
from crontab import CronTab cron = CronTab(user = "aayussss2101" ) job1 = cron.new(command = "python3 test1.py" ) job1.minute.every( 2 ) job2 = cron.new(command = "python3 test2.py" ) job2.minute.every( 1 ) cron.write() |
Here is the content of the test.txt file after a few minutes after executing the above python code to create multiple jobs.