Run python every 2 seconds

I know how to start a function every x seconds or minute. The main problem is that it happens that my script stops for « no reason » or that windows crashs. Ram was ok at that time. I can’t let this happens. So instead of running the script forever and call a function every 2 or 3 seconds to check my gmail emails or make it sleep every 2 seconds, I am looking for one of these alternatives :

  • Windows: at email reception (gmail), run my script and read its header
  • Windows: open and run the script every 3 seconds to check for new emails then close it.
  • Other alternatives (web service or other)

Zapier was a good alternative. At email reception (api) run python. But it’s not possible to import library so that doesn’t fit my needs.

I’m working on MacOS so I know I have the possibility to run it with crontab but this not an option since I don’t want to make it run forever on my desk.

Answer

You could use the shedule library: https://schedule.readthedocs.io/en/stable/. Here it’s an example:

import schedule

schedule.every(interval).seconds.do(function)
while True:
     schedule.run_pending()

You need to install the library: pip install schedule

Leave a Reply

Your email address will not be published. Required fields are marked *