Running a Bash Script in a Cron Job: Python Falcon Crontab

In my last post I talked about how I built my own login system, handled user passwords, authenticated users when they tried to sign in, and stored a session variable on their device so they didn’t have to login to the app every time. In this post, I am going to talk about setting up a cron job to run a bash script to update user values in the database on a regular basis.

First, I created a new python script with the following shebang at the top:

#!/my_dir/venv/lib python3.5

This tells the script where to find my python installation. Then, I run the script every day at the same time, so I pull all data from the database within the past 24 hours to update the values in my database.

import time
last_time = time.time() – 24 * 60 * 60

Once I have all of the new data from my database, I make some calculations and then update values in my database based on the updated data. To update data in my MongoDB, I use the following code:

connection[‘databaseName’][‘collectionName’].update({“initialKeyValue”:documentObjectId},{“$set”: { “secondLevelKey” : value , “anotherSecondLevelKey” : value2 } } )

Now, I’m creating a bash script to run in my cron job. The bash script looks like the following:

. /directory/to/my/virtual/environment/activate

# virtualenv is now active, which means your PATH has been modified.
# Don’t try to run python from /usr/bin/python, just run “python” and
# let the PATH figure out which version to run (based on what your
# virtualenv has configured).
cd creativity_app

Now that the bash script is ready, I edited my crontab file using crontab -e. Then, I used the to figure out the crontab syntax for how to run my script every day in the early morning (MST) ( The appropriate syntax is:

25 3 * * * . path/to/my/bash/script/

Meaning it will run my bash script at 3:25am every day.

And that’s it. I have set up a cron job to run a bash script which activates my virtual environment and runs a python script every day at 3:25am. I’m using this cron job to update values in my database that depend on daily responses being submitted to the database.

Leave a Comment

Your email address will not be published. Required fields are marked *