Rougher
Rougher

Reputation: 848

Insensitive to time zone changes Timer in Python

In my peripheral device I use python Timer:

timer = Timer(45, my_func, [])
timer.start()

The problem is during Timer running, device time zone can be changed (due to a device is connected to WIFI), and timer will be stopped immediately.

Does an another way exist that is insensitive to time zone changes?

I use Python 3.7.3

Upvotes: 0

Views: 68

Answers (1)

Amit Yungman
Amit Yungman

Reputation: 381

You can wrap your function with a timer, and just use regular Thread.
Example code:

from threading import Thread
import time


def wrapper_func(seconds: float, func, args: dict, sleep_interval_seconds: float = 0.1):
    seconds_left = seconds
    while seconds_left >= 0:
        time.sleep(sleep_interval_seconds)
        seconds_left -= sleep_interval_seconds
    if args:
        func(**args)
    else:
        func()


def timed_thread(seconds: float, target, func_args: dict = None) -> Thread:
    return Thread(target=wrapper_func, args=(seconds, target, func_args))


def funcc():
    print("BBBBBB")


t = timed_thread(3, funcc)
t.start()

print("AAAAA")
time.sleep(4)
print("CCCCC")

Will print:

AAAAA
BBBBBB
CCCCC

Upvotes: 1

Related Questions