Forums

Weekly scheduled task

Hi

What would be the easiest way to run a scheduled task weekly? I see the current options are for daily/hourly.

I want to run a script each Monday morning only.

Ta Richard

Figured it out.

import datetime
today = datetime.date.today()
weekday = today.weekday()

if (weekday == 0):
    run my script

: )

sounds like that'll work!

Did it work?

Sure did :)

:-)

Where to you place that script for a Monday morning run? The command line in the Scheduled Tasks bar doesn't seem to allow multiple lines of code.

Put it in a file and then execute the file from the scheduled task.

How do implement "run my script"?

I've tried:

if (weekday == 0)
    import foo.py

That doesn't seem to work.

foo.py is not a valid import. If you're trying to import a file called foo.py and it's on your python path, then you need

import foo

Sorry guys for writing my question here but I tried what richyvk wrote. I wrote the code below to send weekly emails to my users. If I place the code into the views.py it works well but if I place the code into a file in my project folder it works not. I run the code on my localhost in VS Code with the "Run Python File" button and it always hits the exception. What am I doing wrong? (sorry if my question doesn't belongs to here)

weeklyemailmm.py

from django.core.mail import send_mail
import datetime

today = datetime.date.today()
weekday = today.weekday()

subject = 'New weekly email'
message = 'Hi there!'

if (weekday == 2):
    try:
        send_mail(
            subject,
            message,
            'example@xy.com',
            ['user@something.com'],
            fail_silently=False,
        )
        print('It is Wednesday, email sent')
    except:
        print('It is not Wednesday')
else:
    print('Email does not sent')

What error are you getting?

It just prints the except (It is not Wednesday) and does not send the email (today I added weekday == 4 to try it).

From the console:

ruszakmiklos@Ruszak-MacBook-Pro MPSA % /usr/local/opt/python@3.9/bin/python3.9 /Users/ruszakmiklos/Documents/GitHub/MPSA/stressz/weeklyemailmm.py
It is not Wednesday

Other days if it not equal with the added day it prints the else (Email does not sent)

If I delete delet the try-except parts it gives this errer:

django.core.exceptions.ImproperlyConfigured: Requested setting EMAIL_BACKEND, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

If you want to use it outside of the web app but use the whole Django infrastructure for it, the best way is to write it as a management command and run it with manage.py. The error you're seing is telling you exactly that it doesn't have access to the Django environment.

Thank you very much!

No problem, glad we could help!