Last active
May 1, 2024 16:08
-
-
Save depado/7925679 to your computer and use it in GitHub Desktop.
Creating and executing a periodic task in Python with no additionnal module (without Celery)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Only dependency needed | |
import threading | |
# Dependency for the task | |
import datetime | |
import time | |
# Function wrapper | |
def periodic_task(interval, times = -1): | |
def outer_wrap(function): | |
def wrap(*args, **kwargs): | |
stop = threading.Event() | |
def inner_wrap(): | |
i = 0 | |
while i != times and not stop.isSet(): | |
stop.wait(interval) | |
function(*args, **kwargs) | |
i += 1 | |
t = threading.Timer(0, inner_wrap) | |
t.daemon = True | |
t.start() | |
return stop | |
return wrap | |
return outer_wrap | |
@periodic_task(10) | |
def my_periodic_task(): | |
# This function is executed every 10 seconds | |
print("I am executed at {}".format(datetime.datetime.now())) | |
# Call the function once to launch the periodic system | |
my_periodic_task() | |
# This task will run while the program is alive, so for testing purpose we're just going to sleep. | |
time.sleep(500) |
I'm glad it did!
gr8 code
It helped me. One correction is that you're missing a closing brace in line no 31 :)
Updated ;) Thanks
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Worked for me brother!