如何用Python写一个每分每时每天的定时程序

 

1.计算生日是星期几

当你女朋友要过生日了,你肯定要定找家饭店订个餐庆祝一下,餐馆工作日会空一些,周末位置不好定,要是能知道她的生日是星期几就好了,下面这个程序就能搞定~~

比如girl friend 的生日假设是 gf_birthday='2017-3-3'

1).我们先把变量格式化成一个datetime对象

birthday=datetime.datetime.strptime(gf_birthday,'%Y-%m-%d')

2).然后利用datetime里面的函数weekday来得到一个下标

birthday.weekday()

3).构造一个weekdays的列表,根据下标从列表里面取出是周几

weekdays=['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']

weekdays[birthday.weekday()]

# -*- coding:utf-8 -*-
# __author: Tiger Lee
# date: 2017/11/10 9:04
# IN Python 3.6


import datetime


def get_birthday_weekday(birthday_str=None):
    weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
    if birthday_str == None:
        birthday = datetime.datetime.today()
        birthday_str = str(datetime.date.today())
    else:
        birthday = datetime.datetime.strptime(birthday_str, '%Y-%m-%d')
    
    print('Your birthday {0} is {1}'.format(birthday_str, weekdays[birthday.weekday()]))

gf_birthday = '2017-9-07'
bf_birthday = '2017-3-3'
get_birthday_weekday(gf_birthday)
get_birthday_weekday(bf_birthday)

 

当然你要计算比如情人节,圣诞节什么的都可以用上面的程序,或者整个列表把10年的节日都罗列计算一下都是可以了,是不是很简单,对日期的理解有木有加深了一下下

 

2.定时任务

在Python里面,比如你想定期去爬一个网页,或者做运维的同学想每天12点去定时download一个文件,或者定时去扫描一些服务器,甚至老板的需求不停的变可能是,每隔5分钟,或者每小时的整点10分,每周每月都有一些定时任务

用Python怎么破很简单,下面这个程序轻松搞定

我们先从一个最简单的例子说,假设我们是每分种的第10秒,去执行一个任务去打印一下当前的目录

1).window下是dir命令,linux是ls

我们用platform这个模块来判断一下操作系统

import platform

os_platfrom=platform.platform()
if os_platfrom.startswith('Darwin'):
    print ('this is mac os system')
    os.system('ls')

elif os_platfrom.startswith('Window'):
    print ('this is win system')
    os.system('dir')

2).如何定时执行

a.我们先获取当前的时间

now=datetime.datetime.now()

假设当前时间是2017-02-09 20:19:47.555000

b.然后我们输入一个你要定时执行的target时间

比如你是x分10秒的时候执行sched_Timer=datetime.datetime(x,x,x,x,x,10)

前面的x是并不重要(只要最后是10秒就行了),我们就把目标时间设的比当前晚一点即可:

sched_Timer=datetime.datetime(2017,2,9,20,20,10)

c.好当时间到了20:20:10的时候要运行我们的程序

如何定时到了呢,很简单用

if now==sched_Timer:
    'run Task'

d.那么如何让时间在下一分钟10秒继续执行呢,也很简单用timedelta()

datetime.timedelta(minutes=1)把target时间往后增加一分钟

sched_Timer=sched_Timer+datetime.timedelta(minutes=1)

然后外边用个while 死循环hold住就可以了

# -*- coding:utf-8 -*-
# __author: Tiger Lee
# date: 2017/11/10 9:05
# IN Python 3.6


import os
import time
import platform
import datetime


def run_task():
    os_platform = platform.platform()

    if os_platform.startswith('Darwin'):
        print('this is mac os system')
        os.system('ls')
    elif os_platform.startswith('Window'):
        print('this is win system')
        os.system('dir')


def timer_fun(sched_timer):
    """
    每隔1秒查看当前时间,与定时任务的时间匹配,如果匹配即执行任务
    :param sched_timer:
    :return:
    """
    flag = 0
    while True:
        time.sleep(1)
        now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        if str(now) == str(sched_timer):
            run_task()
            flag = 1
        else:
            if flag == 1:
                # sched_timer = sched_timer+datetime.timedelta(days=1)
                sched_timer = sched_timer+datetime.timedelta(minutes=1)
                flag = 0


if __name__ == '__main__':
    sched_timer = datetime.datetime(2017, 11, 9, 15, 25, 00)
    timer_fun(sched_timer)

 



posted @ 2017-11-10 09:06  tiger_li  阅读(249)  评论(0)    收藏  举报