DEV Community

loading...

Python Scheduler: A cron job replacement

damjand profile image Damjan Dimitrov ・2 min read

In this post I would like to show you a more convenient way of scheduling tasks to execute on a given time period.

Cron jobs are commands which are performed in a set time interval, it can be every minute, every hour, every third day, once a week etc.
Sometimes the process of creating and setting up a cron job might appear to be tedious and complicated. I've found an awesome python module for doing exactly what a cron job does but in a way cooler and more fun way.

The module is called schedule and according to its official documentation, it is designed to be very understandable by a human. Here's how it looks:

Now, let's say we have a real life problem we need to solve and keep doing that periodically. As an example, I've made a script which checks for empty folders in a given path. This might appear to be a mess for someone who forgets to delete empty folders, keeps rearranging files and other scenarios. This is how the schedule module looks like in action:

Now, the last thing we need to consider: the scheduler is running only as long as we have our program open and running. When we close or stop the program, the scheduler is cut off and no longer checks for the time interval in the background.
As a solution for this, we can use the nohup command, which stands for no hangup and makes a process immune to hangups (in our case the hangup means stopping the script from running).
We have our scheduler.py file ready with the task we want to be executing in our timeline. These are the steps you should take in order to have the desired result:

  • Install the schedule module via pip by running pip install schedule , preferrably in your virtual environment
  • At the top of your script add #!/usr/bin/env python3 . This step is necessary if you have multiple versions of Python installed and /usr/bin/env will ensure that the first Python interpreter in your $PATH environment variable is taken.
  • In the terminal, run chmod +x scheduler.py , which will grant the required file permissions for continuous execution
  • Run the command nohup /path/to/scheduler.py & . The '&' symbol ensures that your script will run in the background as a system process.

Congrats, you now have your script running in the background. You can feel free to close the terminal and do something else while your script will check for the time period uninterruptedly. If you want to stop script from running, you can list the processes and find its id with the command

ps ax | grep scheduler.py

which shows you the process' PID and then run

kill PID

Source

Note: This was developed and tested only on a MacOS system

Discussion (1)

pic
Editor guide
Collapse
aabiseverywhere profile image
Aabishkar Wagle

Good one. Thanks.