使用场景:每一个task都有一个时间戳,然后写入redis中,redis服务zrangebyscore会按照时间范围进行查找,弹出现在范围内的task_id.
import time
import datetime
import redis
import random
from flask import request
import io
import os
from flask import Response
app = Flask(__name__)
r = redis.Redis()
task_dick = {}
@app.route('/add2',methods=['POST','GET'])
def start1():
if request.method == 'GET':
print('redis======')
start_app()
return "ok"
@app.route('/add',methods=['POST','GET'])
def add():
if request.method == 'GET':
print("生成任务时间号==========")
global task_dick
a=random.randint(0,9)
b=random.randint(0,9)
c=random.randint(0,9)
d=random.randint(0,9)
name="task"+str(a)+str(b)+str(c)+str(d)
task_id = str(name)
task_value=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
task_value_str =time_str_2_timestamp(task_value)
task_dick[name]=task_value_str
print("生成的任务",task_dick)
#b()
return 'ok'
def time_str_2_timestamp(time_str):
time_obj = datetime.datetime.strptime(time_str,'%Y-%m-%d %H:%M:%S')
timestamp=time_obj.timestamp()
return timestamp
def start_app():
print('开始遍历,向数据库写入',task_dick)
print("查看全局数据,是否存在",task_dick)
for key in task_dick:
print("存在数据,添加中。。。。。。。")
time_str = task_dick[key]
#time_str1=str(time_str)
print("key=========",key)
print('value======="',time_str)
r.zadd('timed_task',key,time_str)
return "写入ok"
if __name__ == '__main__':
app.run(host='192.168.56.102',port='5000',debug=True)
mport time
import time
import datetime
from flask import Flask
import time
import datetime
import redis
r = redis.Redis()
while True:
now = datetime.datetime.now()
#print('当前时间---now',now)
now_lower = now.replace(second=0,microsecond=0)
#print('当前时间去0--now_lower',now_lower)
now_higher = now_lower + datetime.timedelta(minutes=1)
#print("下一分钟时间·----now_higher",now_higher)
#bb = datetime.timedelta(minutes=1)
#print('拼接的时间尾巴',bb)
#print("时间上线---",now_lower.timestamp())
#print("时间下线---",now_higher.timestamp())
#print("时间类型---",type(now_higher.timestamp()))
#a=now_lower.timestamp()
#b=a-30
#c=a-60
#task_value=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
#task_value_str =time_str_2_timestamp(task_value)
#task_value_str1=task_value_str
#task_value_str2=task_value_str+30
task_for_this_minute=r.zrangebyscore('timed_task',now_lower.timestamp(),now_higher.timestamp(),0,1000,withscores=True)
print('现在运行的任务=========',task_for_this_minute)
time.sleep(5)