標籤:
1 #!/usr/bin/python 2 # -*- coding=utf-8 -*- 3 import time 4 import os 5 import datetime 6 import threading 7 from time import ctime,sleep 8 9 date=time.strftime(‘%Y-%m-%d‘,time.localtime(time.time()))10 dbname=(‘test‘,‘test2‘) #定義元組必須要有多個,要不則迴圈裡面的字元。11 dbname2=(‘test3‘,‘test4‘)12 bkdir="/backup/mysqlbk/"13 14 #刪除超過3天的備份檔案15 now_time = datetime.datetime.now()16 yes_time = now_time + datetime.timedelta(days=-3)17 out_time = yes_time.strftime(‘%Y-%m-%d‘)18 19 20 21 22 def dumpsql():23 for i in dbname:24 os.system("/usr/local/mysql/bin/mysqldump -u%s %s | gzip > %s%s" % ("root",i,bkdir,date+"."+i+".sql.gz"))25 26 def dumpsql2():27 for i in dbname2:28 os.system("/usr/local/mysql/bin/mysqldump -u%s %s | gzip > %s%s" % ("root",i,bkdir,date+"."+i+".sql.gz"))29 30 31 def outbk():32 for i in dbname:33 if os.path.exists(bkdir+out_time+‘.‘+i+‘.sql.gz‘):34 os.remove(bkdir+out_time+‘.‘+i+‘.sql.gz‘)35 36 #雙線程37 threads=[]38 t1 = threading.Thread(target=dumpsql)39 threads.append(t1)40 t2 = threading.Thread(target=dumpsql2)41 threads.append(t2)42 43 if __name__ == "__main__":44 outbk()45 for t in threads:46 t.setDaemon(True) #啟動多線程47 t.start()48 t.join()49 print ("all over %s" %ctime())
學以致用,python多線程備份資料庫並刪除舊的備份。