Forums

How can I run a cron job for every 2 or 5 seconds.

Hey, I have a script which checks twitter for any new tweet with a particular hashtag. I want to run that script for like every second or atleast 5 seconds through cron job. Is that possible through pythonanywhere? If yes? then how?

Regards, pruthvi

Probably the best way to do this is to have a constantly-running task with a check-sleep-check-sleep kind of loop. This page gives a useful way to write a long-running task like that in a way that means it's restarted if it ever crashes.

Hi I am looking at running a task monthly (12:00 on the 15th of every month). What would you suggest seeing that tasks can only do Daily or Hourly?

The easiest way to do that would be to scheduled it to run at 12:00 every day, and then at the start of the script, check the date and exit immediately if it's not the 15th. Something like this:

from datetime import datetime
import sys

if datetime.today().day != 15:
    sys.exit()

Ah ok great makes sense thanks. I am getting an error on site though. When I run the command via pycharms 'python manage.py shell' it runs fine but on PA I get the error "django.core.exceptions.ImproperlyConfigured: Requested setting AUTH_USER_MODEL, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings." when trying to access my user.

Are you using python manage.py shell on PythonAnywhere? It's a Django thing, not a pycharm thing, and you need to run your Django scripts that way both locally and on PythonAnywheere -- trying to run them directly with python myscript.py will generate the error message you describe.

Hi Giles. Ok I think I understand. I run the .py file in pycharm using 'python manage.py shell'. I then assume because it works there it should run as a task on PA simply by stating the path to the file i.e. 'python3.6 /home/josh87/newmintv2/dashboard/schedules.py' . I have tried without the python3.6 prefix and also by running with virtualenv. How do you suggest running it on PA the same way the shell does on PyCharm?

See this. You will need to first go to the correct folder/path, and then run the setup.

Hmm I added the following:

import django
from django.conf import settings
from dashboard import dashboard_defaults
settings.configure(default_settings=dashboard_defaults, DEBUG=True)
django.setup()

and I get:

ModuleNotFoundError: No module named 'dashboard'

[edited by admin: formatting]

I don't think that this is what you want. Instead you may want to do something like this:

# assuming your Django settings file is at '/home/myusername/mysite/mysite/settings.py'
path = '/home/myusername/mysite'
if path not in sys.path:
    sys.path.append(path)
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'   
import django
django.setup()

But either way the key is adding the correct directory to sys.path

Ok, I feel like we're close ;). After importing os and sys and running the file in the environment I get the following when importing from models:

...
from .models import s9wallet, Riglet
ModuleNotFoundError: No module named '__main__.models'; '__main__' is not a package

Hmm, I think Conrad might have sent you down a blind alley with this!

Instead of trying to set up the Django settings in your script, it's best to write a Django management command. That will do all of the setup for you and means that you don't need to do any special configuration; you can just put code into it that would work in manage.py shell.

As an aside: manage.py shell is a general Django thing, not PyCharm-specific -- if you've installed your Django app into /home/josh87/mydjangosite then running /home/josh87/mydjangosite/manage.py shell will give you a shell where you can do stuff just like you can locally -- of course, that's useful interactively, but we're talking about scheduling things here, so it's not what we need.

Anyway, to write a management command, you need to create a file inside your Django project. Let's say you have an app inside your mydjangosite project called myapp, so it's stored in the directory /home/josh87/mydjangosite/myapp/. Inside that directory, you create a directory called management, and inside there you create one called commands. Finally, in there, you create a Python file called, say, mycommand.py. In that file, you can put code like this:

from datetime import datetime
import sys

from django.core.management.base import BaseCommand
# Import your Django models here

class Command(BaseCommand):
    help = 'Runs my special command'

    def add_arguments(self, parser):
        pass

    def handle(self, *args, **options):
        if datetime.today().day != 15:
            sys.exit()
         # Your Django code goes here

Once you've done that, you'll have a new thing you can run using manage.py -- if you schedule the script

/home/josh87/mydjangosite/manage.py mycommand

...then it will run the Django code in the handle function.

The full documentation for Django management commands is here.

Hi there, worked like a charm, I just had to run the task in the environment. Thank you!

Excellent! Glad we could help.

Hello PythonAnywhere,

I would like to know that if I am on the free tier and running the script using the Django management commands explained by Giles and using Python time module sleep method for 7days, so that script run every 7 days, then will it run continuously or it will crash while running.

Thanks for the great service

It will be stopped. Use a daily task and have a check at the start f the script to see whether it's a day it should run on.

So like if I will do

sys.exit()

then I don't have to start the script again by myself?

That's correct. It will be run again at its next scheduled time.

Thanks for the information