PYTHON set timed tasks

I have lost a single chip before. The main task is:
wait for XX seconds, wake up the XX process to perform the XX operation, and if it meets, execute the XX program.

Python has always used this operation when executing this kind of program before:

while 1:
     time.sleep(10)
     # 主进程
     XXXX
def func():
    while 1:
        time.sleep(5):
        XXXXXX
t1 = threading.Thread(target=func)
t1.setDaemon(True)
t1.start()

It is the main process + sleep().
I don't know if this algorithm is particularly good, but I will only write these...
or use the clock to compare the current time with the set time, if the time is greater than or equal to the current time, execute the program and reset the timing.

I'm more dishes, and I won't be timing if I leave the time module.
——————————————————————————

Today I want to operate a program, the main business logic is similar:
operate once every six hours, and then refresh the timing. If it is manually operated, reset the timing.

But how does sleep() reset the timing? ?

After thinking for an hour, I made a program:

time_get = 0


def time_flash(end_time=300, flash_time=2):
    global time_get
    time.sleep(flash_time)
    time_get = time_get + flash_time
    if time_get <= end_time:
        return False
    else:
        time_get = 0
        return True


When using:

while 1if time_flash(300):
        XXXXXXXX

Obviously, this program looks useless. But time_get can be modified at any time during timing.

For example: I want to use a program to stop sleep() and let the program execute immediately.
Normally it is difficult (because the program is sleeping and does not receive any data)
you can define:

time_get = 1000

The program can stop sleep() within 2 seconds and execute immediately.
After the execution of this process, return to the 300-second timed task.

In general, I think it's OK.
Waiting for a better way.

TIP: The timing is not 300S, because it takes time to execute the program. The program waits for 300S.
But most timed tasks have no requirement to be accurate to the second.

I use this algorithm on github:
Insert picture description here

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_45642669/article/details/114257858