Python3.6 Schedule模組定時任務(執行個體講解),python3.6schedule

來源:互聯網
上載者:User

Python3.6 Schedule模組定時任務(執行個體講解),python3.6schedule

一,編程環境

PyCharm2016,Anaconda3 Python3.6

需要安裝schedule模組,該模組網址:https://pypi.python.org/pypi/schedule

開啟Anaconda Prompt,輸入:conda install schedule 提示:Package Not Found Error

於是,使用 pip 安裝。由於Anaconda3 中已經內建了pip,如:

於是 cmd 命令列切換到 scripts 目錄,執行 pip.exe install schedule 安裝成功。這樣就可以在PyCharm裡面 import schedule 了

二, 在每天某個指定的時間點上,從資料庫中尋找資料然後寫入 csv 檔案

①使用 sqlalchemy 模組來建立資料庫連接,關於windows 下 python3.6 for mysql 驅動安裝,可參考:windows10 下使用Pycharm2016 基於Anaconda3 Python3.6 安裝Mysql驅動總結

②使用schedule 模組來執行循環性任務。關於該模組的用法,可參考官網樣本。

③使用csv模組將查詢到的記錄寫入檔案

整個完整代碼如下:

import scheduleimport codecsimport csvimport timefrom sqlalchemy import create_enginedef get_conn(): engine = create_engine("mysql+pymysql://root:password@localhost:3306/test?charset=utf8mb4") conn = engine.connect() return conndef query(): sql = "select * from user limit 10" conn = get_conn() return conn.execute(sql)def read_mysql_to_csv(filename): with codecs.open(filename=filename, mode='w') as f:  write = csv.writer(f, dialect='excel')  results = query()  for result in results:   write.writerow(result)schedule.every().day.at("17:49").do(read_mysql_to_csv, "test")while True: schedule.run_pending() time.sleep(10)

三,總結

schedule 模組可以非常方便地實現:周期性地在每天的某個時間點上執行任務。其官方樣本如下:

import scheduleimport timedef job(): print("I'm working...")schedule.every(10).minutes.do(job)schedule.every().hour.do(job)schedule.every().day.at("10:30").do(job)schedule.every().monday.do(job)schedule.every().wednesday.at("13:15").do(job)while True: schedule.run_pending() time.sleep(1)

以上這篇Python3.6 Schedule模組定時任務(執行個體講解)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.