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.
Create Multiple jobs using python-crontab
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.