How to Execute a Cron Job on Mac with Crontab
Tags: python, cron, mac, crontab
Published: 2020-02-17 17:17:13

<h1>Prologue</h1>

Before I write the steps below, I would recommend installing the latest version of Python with homebrew. <a href="https://brew.sh/">Homebrew</a> is a package manager just like pip and anaconda and frankly, I’m just using that in this example because I tried for hours to run a simple cron job to no avail. I frequently got errors about not being able to open the file I wanted to execute or not finding the installed python version. I won’t get into my errors in this post but you’re free to use any other Python installation if you like.

I uninstalled my Python 3.x versions I had installed (via pip and conda) and started from scratch — uninstalling was also a hassle. So let’s say you’re on your Mac and have the default Python distribution which I believe should be 2.7.10. Few to no developers are updating modules in this version so when you’re building projects, it’s best to have the latest version of Python installed.

I followed <a href="https://realpython.com/installing-python/#step-2-install-homebrew-part-2">Real Python’s guide</a> to install Python 3 via Homebrew (a quick few steps really) so I will assume you have done the same going forward in this post.

<h1>Steps</h1>

Open up your Terminal command prompt on your Mac and navigate to the home directory by running <code>cd ~/</code>

For me, it is <code>Users/Nakul</code>

We will be using Mac OS’s in-built crontab feature to write our cron jobs.

Type <code>crontab -e</code> and press Enter.

This should open up an empty file, this is where you will write your cron jobs. You can write the job to run a shell script or a Python script in this case.

Type <code>:q!</code> to exit the editor.

Assuming you followed the Homebrew guide above, double check your Python installation path. You can do so by typing <code>which python3</code> in your Terminal. It should display <code>/usr/local/bin/python3</code> (which is an alias for the actual homebrew installation location but that’s fine, we won’t go into that right now). You will include this path in your cron job syntax, which we’ll get into.

Before we write our cron job, we should have a script which we want to run.

I’ve already created a directory <code>/Documents/Python/cron</code> in my home directory and created a simple script called <code>cron_test.py</code>

> Note: this Python script needs to be executable so change the permissions on it to allow for that, I just ran a chmod 777 cron_test.py

The <code>cron_test.py</code> script simply creates a directory with the current date and time as the name.

The script text is as follows if you want to use the same script:

<code>
```python
#!/usr/bin/python3
from datetime import datetime
import os
sysDate = datetime.now()
# convert system date to string
curSysDate = (str(sysDate))
# parse the date only from the string
curDate = curSysDate[0:10]
# parse the hour only from the string
curHour = curSysDate[11:13]
# parse the minutes only from the string
curMin = curSysDate[14:16]
# concatenate hour and minute with underscore
curTime = curHour + ‘_’ + curMin
# val for the folder name
folderName = curDate + ‘_’ + curTime
# make a directory
os.mkdir(folderName)
```
</code>

You might wonder what that first line <code>#!/usr/bin/python3</code> is. That line is referred to as a shebang and how the cron job will interpret the script so in this case it will run the cron_test.py with Python (as if you executed python <code>cron_test.py</code> in your Terminal).

Ok, so we have Python 3.x installed, we have a Python script, now let’s write the cron job to run this!

Let’s say we want to run this script every minute (mostly for the purpose of testing on your end so you can see the results without waiting too long).

The cron job syntax is as follows:

<code>*/1 * * * * cd ~/Documents/Python/cron && /usr/local/bin/python3 cron_test.py >> ~/Documents/Python/cron/cron.txt 2>&1</code>

What does the above mean? Let’s analyze it quickly.

<code>*/1 * * * *</code> simply means that the job will run every minute.

<code>cd ~/Documents/Python/cron && /usr/local/bin/python3</code> navigates to the directory where the script you want to execute is located and specifies to use Python instead of Bash to execute (since it is a Python script, also remember that we added the shebang within the script, I found that it needed to be in both places to work).

<code>cron_test.py</code> is the script filename.

<code>>> ~/Documents/Python/cron/cron.txt</code> specifies where to output the logs in case the execution of the job has any issues.

<code>2>&1</code> simply disables email because by default, the cron job will try to send an email but we don’t have an address specified.

Anyway, that should be enough to get you writing and testing your scripts, so go on!

Feel free to browse the web to learn more about cron jobs and crontab. I decided to write this for those who have a fundamental understanding of programming and wanted to write a cron job as soon as possible.

Hope this helped; go write some jobs!
Find me on the web:

<a href="https://www.linkedin.com/in/nakulkurane/">Follow on LinkedIn</a>