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