[Python] How to run scheduler job daily with start and end time using AsyncIOScheduler in...

Discussão em 'Python' iniciado por Stack, Setembro 27, 2024.

  1. Stack

    Stack Membro Participativo

    I am using FastAPI and using AsyncIOScheduler. My scheduler condition is: Run the task everyday at 6 am with start_time =6 Am and end time is 8 am.

    I have added scheduler code in lifespan in which your code is executed only once when the application started. Please refer code where I have added datetime.now() to get start and end time but it will execute only once because added it in lifespan so how can I execute job everyday.

    @asynccontextmanager
    async def lifespan(app: FastAPI):
    # Run at startup

    def print_hello():
    print("Hello", datetime.now())
    from apscheduler.schedulers.asyncio import AsyncIOScheduler
    from datetime import datetime, timedelta
    scheduler = AsyncIOScheduler()
    print("Datetime.......",datetime.now())
    start_time = datetime.now() + timedelta(seconds=5) # Start in 10 seconds
    end_time = datetime.now() + timedelta(seconds=15) # End in 60 seconds
    scheduler.add_job(print_hello, "interval", start =start_time, end = end_time, seconds=1)
    scheduler.add_job(print_hello, 'cron', hour=6, minute=0)
    scheduler.start()

    yield
    # Run on shutdown (if required)
    scheduler.shutdown()

    Continue reading...

Compartilhe esta Página