Shreyash Sharma
Shreyash Sharma

Reputation: 318

How to make a function run for specific duration periodically

I want to take a screenshot every second for 10 secs.

I have tried using threading and schedule but I've not been able to come up with the solution to satisfy my problem.

def fun(original):
    end_time = datetime.now() + timedelta(seconds=10)
    while datetime.now() < end_time:
        current = ImageGrab.grab()
        current.save("current.png")
        current = cv2.imread("current.png")
        found = screenshot_comparison(original,current)
        if found :
            print("matched")
        else :
            print("didntMATCH")
            fun(original)

I want to take screenshots every second for 10 secs and match it with an already grabbed screenshot.

Upvotes: 4

Views: 244

Answers (1)

Lucan
Lucan

Reputation: 3635

I would suggest utilizing the Advanced Python Scheduler and more specifically, use their interval scheduler, for example:

sched = BlockingScheduler()
sched.add_job(yourFunction, 'interval', seconds=10)
sched.start()

EDIT Here's a more complete example:

from apscheduler.schedulers.blocking import BlockingScheduler

sched = BlockingScheduler()

def myFunction(testParam):
    print("Message: {}".format(testParam))

if __name__ == '__main__':
    sched.add_job(myFunction, 'interval', seconds=10, args=["Works!"])
    sched.start()

Upvotes: 4

Related Questions