How to Schedule a Python Script on a Mac

TheAutomatic.net

Contributor:
TheAutomatic.net
Visit: TheAutomatic.net

By:

Blogger, TheAutomatic.net, and Senior Data Scientist

In a previous article, we talked about how to run Python from the Windows Task Scheduler. This post will cover how to schedule Python tasks on a Mac operating system as well as give an overview of the schedule package.

Using crontab on Mac

Python tasks can be scheduled on Mac using crontab. To do that, first, open up the Terminal. Then, we need to modify the crontab file. We can do that by typing crontab -e.

This will open crontab in the default editor, which is typically vim. You can change the editor by adding the editor name in front of our command – for example, to modify the crontab file using nano, we can run nano crontab -e (followed by enter).

Next, we need to add in a line describing the schedule frequency of how often we want the Python script to run. We input this in the order: minute, hour, day of the month, month, and day of the week. To leave one of these unspecified, place an asterisk (*) in that date / time slot.

Example 1: Run script on the first day of each month at 2:03.

	
3 2 1 * * python /path/to/test_script.py

Example 2: Run script every minute

	
* * * * * python /path/to/test_script.py

Example 3: Run script every hour at the 30th minute

30 * * * * python /path/to/test_script.py

Once you’ve scheduled your Python script, you need to save the crontab file. If you’re using nano, you can do that by typing ctrl+0 followed by ctrl+x to exit. In vim, you can save and exit by hitting esc and then typing :w, followed by enter.

Handling potential issues

One issue that may come up has to do with permissions with “full disk access”. This may happen if you’re using a recent version of macOS Mojave. For details on how to fix this issue, see here.

Another common issue that occurs is with path names. This is always good to check – for example, if you have multiple installations of Python installed, you’ll want to point to the correct installation needed for your scheduled job.

The schedule package

In addition to using crontab to run Python scripts, we can also use the schedule library for handling scheduling Python tasks. This package is especially useful for scheduling specific functions within Python applications. It also works across different operating systems. Let’s get started with the schedule package by installing it with pip:

pip install schedule

We’ll start by creating a simple function called test that simply prints out a message. Then, we can use schedule to schedule a task running this function every 10 seconds. To kick off this task, we can use the run_pending method, which will run inside of a while loop.

import schedule
 
def test():
    print("Test this out!")
 
schedule.every(10).seconds.do(test)
 
while True:
    schedule.run_pending()

The recurrence of the task can be adjusted by changing “seconds” to “minutes” or “hours” like below.

# every 10 minutes
schedule.every(10).minutes.do(test)
 
# every 10 hours
schedule.every(10).hours.do(test)

Likewise, we can change the time unit length from 10 to any other number.

# every 1 minute
schedule.every(1).minutes.do(test)
 
# every 30 seconds
schedule.every(30).seconds.do(test)

Listing and clearing tasks

You can print out a list of the scheduled tasks by running schedule.jobs:

schedule.jobs

To clear out all tasks from the scheduler, we can run the following line of code:

schedule.clear()

Learn more about schedule by clicking here.

Scheduling Python tasks from the Windows Task Scheduler

If you’re running on Windows, you can also schedule tasks via the built-in Task Scheduler. Learn more about how to do that by clicking here.

Conclusion

That covers it for this post. Check out other Python posts here.

Visit TheAutomatic.net for additional insight

Disclosure: Interactive Brokers

Information posted on IBKR Traders’ Insight that is provided by third-parties and not by Interactive Brokers does NOT constitute a recommendation by Interactive Brokers that you should contract for the services of that third party. Third-party participants who contribute to IBKR Traders’ Insight are independent of Interactive Brokers and Interactive Brokers does not make any representations or warranties concerning the services offered, their past or future performance, or the accuracy of the information provided by the third party. Past performance is no guarantee of future results.

This material is from TheAutomatic.net and is being posted with permission from TheAutomatic.net. The views expressed in this material are solely those of the author and/or TheAutomatic.net and IBKR is not endorsing or recommending any investment or trading discussed in the material. This material is not and should not be construed as an offer to sell or the solicitation of an offer to buy any security. To the extent that this material discusses general market activity, industry or sector trends or other broad based economic or political conditions, it should not be construed as research or investment advice. To the extent that it includes references to specific securities, commodities, currencies, or other instruments, those references do not constitute a recommendation to buy, sell or hold such security. This material does not and is not intended to take into account the particular financial conditions, investment objectives or requirements of individual customers. Before acting on this material, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice.

In accordance with EU regulation: The statements in this document shall not be considered as an objective or independent explanation of the matters. Please note that this document (a) has not been prepared in accordance with legal requirements designed to promote the independence of investment research, and (b) is not subject to any prohibition on dealing ahead of the dissemination or publication of investment research.

Any trading symbols displayed are for illustrative purposes only and are not intended to portray recommendations.