Reputation: 53943
I'm using APScheduler to run some recurring tasks as follows:
from apscheduler.scheduler import Scheduler
from time import time, sleep
apsched = Scheduler()
apsched.start()
def doSomethingRecurring():
pass # Do something really interesting here..
apsched.add_interval_job(doSomethingRecurring, seconds=2)
while True:
sleep(10)
Because the interval_job ends when this script ends I simply added the ending while True
loop. I don't really know if this is the best, let alone pythonic way to do this though. Is there a "better" way of doing this? All tips are welcome!
Upvotes: 0
Views: 4232
Reputation: 1057
Try using the blocking scheduler. apsched.start() will just block. You have to set it up before starting.
EDIT: Some pseudocode in response to the comment.
apsched = BlockingScheduler()
def doSomethingRecurring():
pass # Do something really interesting here..
apsched.add_job(doSomethingRecurring, trigger='interval', seconds=2)
apsched.start() # will block
Upvotes: 1
Reputation: 179
Try this code. it runs a python script as a daemon :
import os
import time
from datetime import datetime
from daemon import runner
class App():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = '/dev/tty'
self.stderr_path = '/dev/tty'
self.pidfile_path = '/var/run/mydaemon.pid'
self.pidfile_timeout = 5
def run(self):
filepath = '/tmp/mydaemon/currenttime.txt'
dirpath = os.path.dirname(filepath)
while True:
if not os.path.exists(dirpath) or not os.path.isdir(dirpath):
os.makedirs(dirpath)
f = open(filepath, 'w')
f.write(datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S'))
f.close()
time.sleep(10)
app = App()
daemon_runner = runner.DaemonRunner(app)
daemon_runner.do_action()
Usage:
> python mydaemon.py
usage: md.py start|stop|restart
> python mydaemon.py start
started with pid 8699
> python mydaemon.py stop
Terminating on signal 15
Upvotes: 1