欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python3.6 Schedule模塊定時任務(實例講解)

 更新時間:2017年11月09日 08:36:04   作者:hapjin  
下面小編就為大家?guī)硪黄狿ython3.6 Schedule模塊定時任務(實例講解)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

一,編程環(huán)境

PyCharm2016,Anaconda3 Python3.6

需要安裝schedule模塊,該模塊網(wǎng)址:https://pypi.python.org/pypi/schedule

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

于是,使用 pip 安裝。由于Anaconda3 中已經(jīng)自帶了pip,如下圖:

于是 cmd 命令行切換到 scripts 目錄,執(zhí)行 pip.exe install schedule 安裝成功。這樣就可以在PyCharm里面 import schedule 了

二, 在每天某個指定的時間點上,從數(shù)據(jù)庫中查找數(shù)據(jù)然后寫入 csv 文件

①使用 sqlalchemy 模塊來建立數(shù)據(jù)庫連接,關于windows 下 python3.6 for mysql 驅(qū)動安裝,可參考:windows10 下使用Pycharm2016 基于Anaconda3 Python3.6 安裝Mysql驅(qū)動總結(jié)

②使用schedule 模塊來執(zhí)行周期性任務。關于該模塊的用法,可參考官網(wǎng)示例

③使用csv模塊將查詢到的記錄寫入文件

整個完整代碼如下:

import schedule
import codecs
import csv
import time
from sqlalchemy import create_engine

def get_conn():
 engine = create_engine("mysql+pymysql://root:password@localhost:3306/test?charset=utf8mb4")
 conn = engine.connect()
 return conn

def 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)

三,總結(jié)

schedule 模塊可以非常方便地實現(xiàn):周期性地在每天的某個時間點上執(zhí)行任務。其官方示例如下:

import schedule
import time

def 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模塊定時任務(實例講解)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

最新評論