Skip to content

Instantly share code, notes, and snippets.

@Depado
Last active February 23, 2023 09:44
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Depado/7925679 to your computer and use it in GitHub Desktop.
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)
# 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)
@coreyborders01
Copy link

Worked for me brother!

@Depado
Copy link
Author

Depado commented Jun 12, 2019

I'm glad it did!

@werpu
Copy link

werpu commented Apr 17, 2020

gr8 code

@jvinaya
Copy link

jvinaya commented Mar 3, 2021

It helped me. One correction is that you're missing a closing brace in line no 31 :)

@Depado
Copy link
Author

Depado commented Mar 5, 2021

Updated ;) Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment