How to run cron jobs for particular function of your django app?

Contents

First of all navigate to the django internal app where your function is located.

Eg. i want to refresh news every 30 mins hence I will navigate to news app in my django project.

cd /var/loksewa/new

Create the management command folder structure: Inside the news app, create the following directories:

mkdir -p management/commands
touch management/commands/__init__.py
touch management/commands/refresh_news.py

Write the custom management command: Edit the refresh_news.py file to call the refresh_news function:

from django.core.management.base import BaseCommand
from news.models import NewsSource
from news.views import AllNewsAPIView

class Command(BaseCommand):
    help = "Refresh news sources every 30 minutes"

    def handle(self, *args, **kwargs):
        try:
            sources_to_refresh = NewsSource.objects.all()  # Fetch all news sources
            refreshed_news = AllNewsAPIView().refresh_news(sources_to_refresh)  # Refresh news
            self.stdout.write(self.style.SUCCESS("News refreshed successfully!"))
        except Exception as e:
            self.stderr.write(self.style.ERROR(f"Error: {str(e)}"))
  • Test the command: Activate your virtual environment:

    source /your_project_env-path/bin/activate

    Run the management command to ensure it works:

    python /your_project_path/manage.py refresh_news

Add the Cron Job

  1. Open the crontab editor:

    crontab -e

  2. Add a cron job to run the command every 30 minutes: Replace /var/loksewa with your project path and /var/loksewa/myenv with your virtual environment path:

    */30 * * * * source /var/loksewa/myenv/bin/activate && python /var/loksewa/manage.py refresh_news >> /var/loksewa/cron_refresh_news.log 2>&1

    • */30 runs the job every 30 minutes.
    • source /var/loksewa/myenv/bin/activate activates the virtual environment.
    • >> /var/loksewa/cron_refresh_news.log 2>&1 logs output to cron_refresh_news.log for debugging.
  3. Save and exit the editor.

Verify the Cron Job

  1. Check if the cron job is active:

    crontab -l

    Ensure you see the cron job you just added.

  2. Check cron logs: Cron logs are usually available in /var/log/syslog. Use the following command to filter relevant logs:

    grep CRON /var/log/syslog

  3. Inspect the output log: After 30 minutes, check the output log:

    cat /var/loksewa/cron_refresh_news.log