python定時重跑獲取數據


做大數據的童鞋經常會寫定時任務跑數據,由於任務之間的依賴(一般都是下游依賴上游的數據產出),所以經常會導致數據獲取失敗,因為很多人發現數據失敗后

都會去查看日志,然后手動去執行自己的任務。下面我實現了一個自動重復執行去數據庫取數,如果失敗后自動重新去獲取,直到把數據獲取到。

建數據表:

1 CREATE TABLE `testtable` (
2   `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
3   `name` varchar(20) NOT NULL,
4   PRIMARY KEY (`id`)
5 ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

開始的時候數據表是空的,等到腳本重試第3秒的時候向數據庫插入數據。以下是python代碼的實現

 1 #!/usr/bin/env python
 2 #-*- coning:utf-8 -*-
 3 
 4 import MySQLdb
 5 from time import sleep
 6 
 7 class GetData(object):
 8     def __init__(self):
 9         self.conn = ''
10         self.host = '127.0.0.1'
11         self.port = 3306
12         self.user = 'root'
13         self.passwd = '123456'
14         self.db = 'test'
15         self.cnum = 5 #set retry number
16 
17     def init_connect(self):
18         self.conn = MySQLdb.connect(host=self.host, user=self.user, passwd=self.passwd, db=self.db, port=self.port,
19 charset='utf8')
20 
21     def get_data(self):
22         self.init_connect()
23         cur = self.conn.cursor()
24         sql = "select * from testtable"
25         cur.execute(sql)
26         rs = cur.fetchall()
27         cur.close()
28         self.conn.close()
29         return rs
30 
31     def run(self):
32         count = 1
33         while (count <= self.cnum):
34             rs = self.get_data()
35             if len(rs) > 0:
36                 print len(rs)
37                 break
38 
39             print count
40             sleep(10)
41             count += 1
42 
43 if __name__ == '__main__':
44     gd = GetData()
45     gd.run()

自己可以手動執行,在代碼執行到第3秒的時候,執行下面的sql

insert into testtable(`name`) values ('123'),('456'),('789'),('1111'),('3222'),('444');

下面是定時的任務的腳本

00 08 * * * cd /home/python/lsh_sync; python getdata.py >> getdata.log 2>&1

OVER!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM