P
P
PiggyPig2018-02-01 02:41:38
Django
PiggyPig, 2018-02-01 02:41:38

How to execute a function at the same time in Django?

The task is as follows: execute the function in views at the same time - let's say, every day at 12:00.
Found this option with Timer

import datetime as dt

def print_text():
    print("Hi!")
nextDay = dt.datetime.now() + dt.timedelta(days=1)
dateString = nextDay.strftime('%d-%m-%Y') + " 12-00-00"
newDate = nextDay.strptime(dateString,'%d-%m-%Y %H-%M-%S')
delay = (newDate - dt.datetime.now()).total_seconds()
Timer(delay, print_text, ()).start()

But will it keep counting at all if the page is refreshed and the timer function is called again accordingly?
Please help me figure it out.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2018-02-01
@PiggyPig

Web application code in Django and many other frameworks is executed only in response to an http request from the user and ends immediately after it returns the response. If the code does not return a response within a few seconds, it will be forcibly terminated by the server. Therefore, even running your code with a timer will not work normally.
The easiest way to do background tasks in Django is to write your own management command and call it with cron . A more advanced and functional way is to use some kind of asynchronous task execution mechanism, such as Celery .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question