【问题标题】:How to use 'schedule' and 'run' together如何同时使用“计划”和“运行”
【发布时间】:2020-09-05 03:20:23
【问题描述】:

我有一个运行作业的计划脚本:

schedule.every(3).seconds.do(jobCheckSmth)

while True:
    schedule.run_pending()
    time.sleep(1)

我想使用 Web 界面来检查它的状态,而不是使用 CLI 上的 print()

run(host='localhost', port=80, debug=True)

但它会阻止代码执行,所以我必须按 Ctrl-C 来打破 webserver 循环以继续运行 while 循环

Bottle v0.12.18 server starting up (using WSGIRefServer())...
Listening on http://localhost:80/ Hit Ctrl-C to quit.

【问题讨论】:

  • 我正在研究线程来完成这项工作......
  • 线程行为wiered...请指教
  • 我猜你将不得不在一个单独的进程上运行你的网络服务器,并通过一些外部更新(json 文件或数据库)将它与你的主进程一起提供
  • 看起来很@SebastienD
  • 你需要了解异步设计,例如bottlepy.org/docs/dev/async.html

标签: python schedule bottle


【解决方案1】:

这是一个非常适合我使用 gevent 将瓶子变成异步的示例。要么是这个,要么你必须在你的瓶子应用程序之外的它自己的线程中运行schedule。但老实说,你应该这样做。

import gevent
from gevent import monkey,spawn as gspawn, sleep as gsleep, socket, signal_handler as sig
monkey.patch_all()
import signal
import arrow
from bottle import Bottle, static_file, get, post, request, response, template, redirect, hook, route, abort
from gevent.pywsgi import WSGIServer
from geventwebsocket.handler import WebSocketHandler

def start():
    def start_thread():
        set()
        while 1:
            try:
                schedule.run_pending()
            except:
                logger.exception('Scheduler Exception')
            gsleep(5) # This is the polling cycle for pending jobs
    print('Scheduler Started...')
    gspawn(start_thread)

def sample():
    gspawn(jobCheckSmth)

def set():
    # schedule.every(180).seconds.do(func)
    schedule.every().day.at("00:00").do(sample)
    logger.info('Started Schedule at {}'.format(arrow.now()))

@get('/')
def app():
    return 'Hello World!'

 if __name__ == '__main__':
    scheduler.start()
    botapp = bottle.app()
    server = WSGIServer(("0.0.0.0", int(port)), botapp , handler_class=WebSocketHandler)
    def shutdown():
        print('Shutting down ...')
        server.stop(timeout=60)
        exit(signal.SIGTERM)
    sig(signal.SIGTERM, shutdown)
    sig(signal.SIGINT, shutdown)
    server.serve_forever()

【讨论】:

  • 感谢您提供详细示例。我会尝试实现这个想法。会及时向大家发布。再次感谢!
  • 用upvote 标记您的回复。我的等级还不够显示。我如何接受你的工作?
猜你喜欢
  • 2018-09-17
  • 2014-07-13
  • 1970-01-01
  • 2015-01-24
  • 2014-01-27
  • 1970-01-01
  • 2022-06-14
  • 2017-09-01
  • 1970-01-01
相关资源
最近更新 更多