Skip to content

Instantly share code, notes, and snippets.

@sankalpjonn
Created October 29, 2018 11:48
Show Gist options
  • Save sankalpjonn/ef748211fa73b0e14cd14b71eb1fa33d to your computer and use it in GitHub Desktop.
Save sankalpjonn/ef748211fa73b0e14cd14b71eb1fa33d to your computer and use it in GitHub Desktop.
import time
from timeloop import Timeloop
from datetime import timedelta
tl = Timeloop()
@tl.job(interval=timedelta(seconds=2))
def sample_job_every_2s():
print "2s job current time : {}".format(time.ctime())
@tl.job(interval=timedelta(seconds=5))
def sample_job_every_5s():
print "5s job current time : {}".format(time.ctime())
@tl.job(interval=timedelta(seconds=10))
def sample_job_every_10s():
print "10s job current time : {}".format(time.ctime())
if __name__ == "__main__":
tl.start(block=True)
#Output:
#2s job current time : Tue Oct 16 17:55:35 2018
#2s job current time : Tue Oct 16 17:55:37 2018
#5s job current time : Tue Oct 16 17:55:38 2018
#2s job current time : Tue Oct 16 17:55:39 2018
#2s job current time : Tue Oct 16 17:55:41 2018
#10s job current time : Tue Oct 16 17:55:43 2018
@todo
Copy link

todo commented Jul 15, 2019

Instead of defining each job manually, I would like to use a factory pattern (or something similar) to setup 10 jobs. However, I am having some troubles setting them up. I was wondering if you can give me a hand.

Here are what I have done so far. I have identified two main problems. Please see the comments below.

from timeloop import Timeloop
from timeloop import job
from datetime import timedelta

tl = Timeloop()

class myJob (job.Job):
   def __init__(self, name):
      threading.Thread.__init__(self)
      self.name = name
   def run(self):
      print "Starting status " + self.name
      process_sf_status(self.name)            # problem #1: this is not working, self.name is not set
      print "Exiting  status " + self.name

@tl.job(interval=timedelta(microseconds=25))
def process_sf_status(jobName):
   # for some reason, jobName is not passed down to this function
    # do something based on the "jobName", the duration of each job will be different
    if status == 200 and json['resp'] == "completed": 
          # problem #2: what's the right way to stop the job, I have tried
          #  1) set an global exitFlag to True, then try to exit in main, this is not working
          #  2) break, this is not working
          #  3) call tl.stop(), this raised an exception (cannot join current thread), then program just stuck.
          #     I tried handle the exception, but it's not working
    else:
          # continue looping

jobs = []

for i in range(10):
   jobs += [myJob('job-'+str(i))]

try:
   tl.start(block=True)
except RuntimeError as err:
   print "finished"

All comments and suggestions are all highly appreciated. Thanks!

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