T
T
tmkbl2021-10-03 16:30:42
Python
tmkbl, 2021-10-03 16:30:42

Which library to use to do a lot of tasks at a given time in Python?

Is there any library that can do the following? You need to create about 400 tasks in a cycle. Each task must be executed once at the specified time and date. I want to do it within the script, and not on any cron's.
The popular schedule library would suit me, but I can’t understand: is it possible to set a task for a certain time and date there ? I did not find something like that ....
Please help))).

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vindicar, 2021-10-03
@tmkbl

Schedule does not take into account the date. But frankly, it's not too difficult to implement on your own.

from typing import Dict, List, Tuple, Callable
import datetime
import time

def time_matches_mask(now: datetime.datetime, mask: Dict[str, float], delta: datetime.timedelta) -> bool:
    'Проверяем, совпало ли текущее время с заданной маской с указанной точностью'
    target = now.replace(**mask)
    return abs(now - target) < delta

jobs: List[Tuple[Dict, Callable, Tuple]] = [] #Список элементов: маска, функция, аргументы

def call_pending(jobs, now: datetime.datetime, delta: datetime.timedelta):
    for mask, func, args in jobs:
        if time_matches_mask(now, mask, delta):
            func(*args)

jobs.append( ({'seconds':30}, print, ('Hello world!',)) ) #когда число секунд = 30, вызвать print('Hello world!')

delta = datetime.timedelta(seconds=1) #с какой точностью измерять время?
while True:
    time.sleep(1)
    call_pending(jobs, datetime.datetime.now(), delta)

True, there are subtleties. It is worth avoiding calls 2 times in a row because of the large delta, you can replace the second cycle with waiting for the nearest task (with interruption if the list of tasks has changed). Well, and so on.

K
kirillinyakin, 2021-10-03
@kirillinyakin

Here

T
tmkbl, 2021-10-03
@tmkbl

Thank you all for your help! But I found a good solution for myself:

import threading
from datetime import datetime, date, time

def func():
    #функция
    return

date = datetime.strptime('2021-10-03 17:55:00') # дата и время выполнения
delay = (date - datetime.now()).total_seconds() # количество секунд до нужного нам времени
threading.Timer(delay, func).start()

Up: did not fit. This method eats too much memory.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question