Skip to content

Commit

Permalink
Add threading support to cron library
Browse files Browse the repository at this point in the history
  • Loading branch information
kgsensei committed Jun 23, 2023
1 parent 4fb5e68 commit 9b4ea0c
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 12 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@

*.pyc
28 changes: 17 additions & 11 deletions cron.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import threading
import time

jobs = []
Expand All @@ -18,20 +19,25 @@ def addJob(function, timeout, args = None):
if(verbose):
print("Cron Job [ {0}('{1}') ] Registered [Running Every {2}s]".format(function.__name__, args, timeout))

def start():
def start(doThread = False):
"""
Start the cron job counter
This is a thread blocking function
:param bool doThread: Should the cron counter run in a thread? Default: False
"""
seconds = 1
while 1:
if doThread:
thread = threading.Thread(target = start)
thread.start()
else:
seconds = 1
while 1:

for job in jobs:
if seconds % job[1] == 0:
if job[2] == None:
job[0]()
else:
job[0](job[2])
for job in jobs:
if seconds % job[1] == 0:
if job[2] == None:
job[0]()
else:
job[0](job[2])

time.sleep(1)
seconds += 1
time.sleep(1)
seconds += 1
10 changes: 9 additions & 1 deletion example.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,14 @@ def time_alert_function(seconds):
cron.addJob(time_alert_function, 1, 1)
# The addJob parameters are; function, timeout/cron delay, args (only 1 supported currently)

# When you're ready to run your cron jobs do this
# When you're ready to run your cron jobs call this function
# Optionally pass 'True' into the function call to make it non-thread blocking,
# Like this: cron.start(True), Default is False or thread blocking.
cron.start()
# It will start the timer to execute your cron jobs

# This will prevent the program from ending if on non-thread blocking mode,
# it will also act as a test to prove cron.start() isn't blocking the thread
input("\n Hello, this is the end of the file!\n\n")
# It contains newline characters so it doesn't get put on the same line as
# other print messages that will come in from the threaded cron jobs.

0 comments on commit 9b4ea0c

Please sign in to comment.