Posts Tagged ‘crons’

Run cron jobs within Django using django-cron

Quite often web applications require cron-like behavior which more or less contradicts with the request-response model.

Not many host providers allow users to create a cron jobs, and even if it is possible, if your site relies on an external script it loses its integrity. It no longer is a website, it is a website relying on cron jobs.

Now at first glance, there is not much difference, but such things make migrating harder and/or may cause a lot of problems in the long run.

As we all know Django is an open source web application framework, designed for rapid development. It follows the so called DRY principle and therefore greatly emphasizes on “pluggability”. In this short tutorial we will show you how to “plug-in” a little but very useful Django application called django-cron, which allows you to easily get cron line behavior.

You can visit the project’s site in at

Installation is fairly easy:

  • Download the source
  • Place django_cron on your python path
  • Add “django_cron” in the list of installed apps in your
  • In the beginning of your global file add:
import django_cron
  • Write your crons in a file named inside the application you want write crons to. Note: The application must be installed in your

A cron job is fairly easy to write.

Here is an example file which deletes old files from a fixed directory:

import os
import time
from django_cron import cronScheduler, Job

class DeleteOldFilesCron(Job):
“””A cron which deletes files older than a minute from a fixed directory”””

    run_every = 60*60*24 # run every day

    def job(self):
        path = ‘/var/www/html/media/tmp/’
        files = os.listdir(path)
        for file in files:
            if(time.time() – os.path.getmtime(path + file) > 60):
                os.remove(path + file)


Naturally you can have several crons in your

Note: There are some Apache specific configurations which must be taken into account. For more information visit

VN:F [1.9.18_1163]
Rating: 3.0/10 (2 votes cast)