Gabriel Moreno
Gabriel Moreno

Reputation: 61

Why doesn't this work? Is this a apscheduler bug?

When I run this it waits a minute then it prints 'Lights on' then waits two minutes and prints 'Lights off'. After that apscheduler seems to go nuts and quickly alternates between the two very fast.

Did i just stumble into a apscheduler bug or why does this happen?

from datetime import datetime, timedelta
import time
import os, signal, logging
logging.basicConfig(level=logging.DEBUG)   

from apscheduler.schedulers.background import BackgroundScheduler
scheduler = BackgroundScheduler()


def turn_on():
    #Turn ON
    print('##############################Lights on')


def turn_off():
    #Turn off
    print('#############################Lights off')


def schedule():
    print('Lights will turn on at'.format(lights_on_time))
if __name__ == '__main__':

    while True:
        lights_on_time = (str(datetime.now() + timedelta(minutes=1)))  
        lights_off_time = (str(datetime.now() + timedelta(minutes=2)))  

        scheduler.add_job(turn_on, 'date', run_date=lights_on_time)
        scheduler.add_job(turn_off, 'date', run_date=lights_off_time)
        try:
            scheduler.start()
            signal.pause()
        except:
            pass

    print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))

    try:
        # This is here to simulate application activity (which keeps the main thread alive).
        while True:
            time.sleep(2)
    except (KeyboardInterrupt, SystemExit):
        # Not strictly necessary if daemonic mode is enabled but should be done if possible
        scheduler.shutdown()

Upvotes: 2

Views: 2221

Answers (2)

Tammo Heeren
Tammo Heeren

Reputation: 2104

Try this:

from datetime import datetime, timedelta
from apscheduler.schedulers.background import BackgroundScheduler
import time

scheduler = BackgroundScheduler()


def turn_on():
    print('Turn on', datetime.now())


def turn_off():
    print('Turn off', datetime.now())


scheduler.start()


while True:
    scheduler.add_job(func=turn_on, trigger='date', next_run_time=datetime.now() + timedelta(minutes=1))
    scheduler.add_job(func=turn_off, trigger='date', next_run_time=datetime.now() + timedelta(minutes=2))
    time.sleep(180)

You should only start the scheduler once.

Upvotes: 1

Tammo Heeren
Tammo Heeren

Reputation: 2104

You are flooding the scheduler with events. You are using the BackgroundScheduler, meaning that scheduler.start() is exiting and not waiting for the event to happen. The simplest fix may be to not use the BackgroundScheduler (use the BlockingScheduler), or put a sleep(180) on your loop.

Upvotes: 2

Related Questions