StayFoolish
StayFoolish

Reputation: 521

python how to run a function everyday at specific time, but can also be terminated

I'm new to explore how to do this in python. What I want to do is run a function every business day at a specific time, e.g., say at 14:55, just 5 minutes before the stock market closes in China. This function will pull some data from a stock market data feeding API and do some simple calculations to generate a signal(-1 means to short, +1 means to long, 0 means don't do anything). I'm not sending the signal yet to make a trade now. I'm just saving the signals everyday to a file locally. Thus, I might be able to collect the signals for 2 weeks or any time I feel like to stop this scheduler.

I notice that APScheduler module being suggested quite often. But I tried it, didn't find a way to make the scheduler stop running 2 weeks after. I only find ways to set up a scheduler to run, maybe every 10 minutes, but it will just keep running a specified function every 10 minutes and can't be stopped programmally, but only through pressing Ctrl+C? For example, I want to run a function every 10 minutes for 6 times, in APScheduler, I didn't see anyway to specify the '6 times' argument. Or I want to run a function every 10 minutes until 1 hour later. I didn't see the '1 hour later' or 'at 16:30' argument either. How to do it?

Currently, I'm doing it this way:

def test_timer():
    '''
    Uses datetime module.
    '''
    running = 1
    stop_time = datetime.now() + timedelta(seconds=60)
    while running:

        print('I\'m working...')
        time.sleep(5)
        running = datetime.now() < stop_time

    print('Goodbye!')

Edited: I'm using python 3.6 in Windows 10.

Upvotes: 1

Views: 6399

Answers (2)

RedEyed
RedEyed

Reputation: 2135

Try this example

from datetime import datetime

from apscheduler.schedulers.background import BackgroundScheduler


def job_function():
    print("Hello World")

sched = BackgroundScheduler()

# Schedule job_function to be called every 1 second
# FIXME: Do not forget to change end_date to actual date
sched.add_job(job_function, 'interval', seconds=1, end_date="2017-09-08 12:22:20")

sched.start()

Update #1

from apscheduler.schedulers.background import BackgroundScheduler

def job_function():
    print("Hello World")

# Here, you can generate your needed days
dates = ["2017-09-08 13:30:20", "2017-09-08 13:31:20", "2017-09-08 13:32:20"]
sched = BackgroundScheduler()                      

for date in dates:
    sched.add_job(job_function, "date", next_run_time=date)

sched.start()

Upvotes: 2

Alex
Alex

Reputation: 163

Looks like a problem for crontab in Linux or Task Scheduler in Windows.

Upvotes: 0

Related Questions