普通闹钟
from time import *
hm = input('hhmm: ').strip()
hh = int(hm[:2])
mm = int(hm[2:])
while True:
print('\r%s' % strftime('%H:%M:%S'), end='')
sleep(1)
if localtime()[3:5] == (hh, mm):
print("\nTime's up\n%02d:%02d" % (hh, mm))
break
定时程序
from time import localtime, sleep
import os
def f1():
print('f1')
def f2():
print('f2')
schedule = {
(19, 3): f1,
(19, 2): f2
}
def main():
while True:
hhmm = localtime()[3:5]
if hhmm in schedule.keys():
sub_pid = os.fork()
if sub_pid < 0:
print('进程创建失败')
elif sub_pid > 0:
print('父进程')
else:
schedule[hhmm]()
print('子进程结束')
sleep(60)
if __name__ == '__main__':
main()
每分钟执行一次
from time import *
last_minute = -1
while True:
sleep(1)
if localtime()[4] != last_minute:
last_minute = localtime()[4]
t = strftime('%Y-%m-%d %H:%M:%S')
print(t, localtime())
每3分钟执行1次
from time import strftime, localtime, sleep
last_3minute = -1
while True:
sleep(1)
if localtime()[4] // 3 != last_3minute:
last_3minute = localtime()[4] // 3
t = strftime('%Y-%m-%d %H:%M:%S')
print(t, localtime())