0

I'll preface this by saying I'm not an advanced programmer and I have only written programs that run sequentially and exit. What I'd like to do now is write a python script that I'll launch and it will run a function every 5 minutes and another function every 10 minutes and do so indefinitely. Here's some pseudo-code:

def RunMeEvery5min:
    do something

def RunMeEvery10min:
    do something

while True:
    every 5 minutes run RunMeEvery5min
    every 10 minutes run RunMeEvery10min
    do this forever until I kill the program

So is this threading? It really doesn't matter if the tasks line up or not as they're essentially unrelated. I would venture to guess that this is a common type of programming question, but I've never really understood how to accomplish this and I don't even know what to search for. Any helpful examples or links to basic tutorials would be much appreciated!

Thanks!

Mike
  • 504
  • 7
  • 23
  • 1
    [ApScheduler](http://apscheduler.readthedocs.io/en/3.3.1/modules/triggers/interval.html#module-apscheduler.triggers.interval), [Celery](http://celery.readthedocs.io/en/latest/), [Django Cron](https://stackoverflow.com/questions/573618/django-set-up-a-scheduled-job) (<-- these are separate links) could get you started. I don't blame you for asking, it's confusing! But it depends on your environment. – Jarad May 10 '18 at 01:40
  • Sounds like something similar to JavaScript's setInterval. I would start by reading similar questions, if so: https://stackoverflow.com/q/2697039/534109 – Tieson T. May 10 '18 at 01:42

2 Answers2

2

Maybe this will help you https://github.com/dbader/schedule

import schedule
import time

def job():
     print("I'm working...")

schedule.every(10).minutes.do(job)

while True:
     schedule.run_pending()
     time.sleep(1)
Wu Wenter
  • 171
  • 5
  • And for me this works well because timing is not critical - I just need stuff to run every so often, somewhat similar to cron jobs, but this is better :) – Mike May 10 '18 at 05:43
0

You can use sched from Python standard library.

import sched, time
from datetime import datetime

scheduler = sched.scheduler(time.time, time.sleep)

def execute_every_05mins():
    print(datetime.now().strftime("%H:%M:%S"))
    scheduler.enter(300, 0, execute_every_05mins, ())

def execute_every_10mins():
    print(datetime.now().strftime("%H:%M:%S"))
    scheduler.enter(600, 0, execute_every_10mins, ())

if __name__ == "__main__":
    scheduler.enter(0, 0, execute_every_05mins, ())
    scheduler.enter(0, 0, execute_every_10mins, ())
    scheduler.run()
stamaimer
  • 6,227
  • 5
  • 34
  • 55