固定时间刷新算法


对于很多app来说都有需要在固定时间刷新的功能,例如游戏中的任务系统,每日任务的话就需要每天固定时间点刷新(每天早上8点刷新);在京东app中也有一个浇水的功能,里面的任务就是每天刷新。

以下代码使用lua实现

一. 每天刷新,假设每天北京时间早上8点刷新。

1. 根据hour来计算下次刷新时间

local time_info = os.date("*t", os.time())

-- 计算出当天的8点时间戳:先算出当天0点时间戳,再加8小时
local today_8_clock = nowTime - (time_info.hour * 3600 + time_info.min * 60 + time_info.sec) + (8*3600)

-- 计算下次刷新时间 nextRefreshTime :
-- 1. 如果当前的hour小于8,那么下次刷新时间就是今天8点;
-- 2. 如果hour大于8,那么刷新时间就是第二天8点,直接加 24*3600
local nextRefreshTime = time_info.hour < 8 and today_8_clock or today_8_clock + (24*3600)

2. 取余法

local nowTime =  os.time()
local time_info = os.date("*t",nowTime)

-- 计算0点到现在的时间跨度
local timeInterval = time_info.hour * 3600 + time_info.min * 60 + time_info.sec

-- 计算下次刷新时间 nextRefreshTime :
local nextRefreshTime = (8*3600 + 24 * 3600 - timeInterval) % (24 * 3600) + nowTime

在这里插入图片描述
nowTime 只有两种可能,8点之前A,8点之后B
那么 nextRefreshTime = A + S1 或者 B + S2
即 nextRefreshTime = nowTime + ( S1 或 S2 )
现在只要把 S1 ,S2 两段距离的计算公式统一成 S3 就行了
即最后要的公式是 nextRefreshTime = nowTime + S3

  • S1 = 8*3600 - timeInterval
  • S2 = 24*3600 - timeInterval + 8*3600 = 8*3600 - timeInterval + 24*3600

整理一下 S1 和 S2 可得到

  • S3 = ( 8*3600 - timeInterval + 24*3600 ) % (24*3600)
    即:
  • S1 = ( 8*3600 - timeInterval + 24*3600 ) % (24*3600)
  • S2 = ( 8*3600 - timeInterval + 24*3600 ) % (24*3600)

所以综上所述,可以得到
nextRefreshTime = nowTime + S3 = nowTime + ( 8*3600 - timeInterval + 24*3600 ) % (24*3600)

二. 每周多次刷新,例如每周三,五,15点刷新

每天刷新相当于每周刷新七次,也可以用这个算法来做

local refresh_list = {3*24*3600 + 15*3600, 5*24*3600 + 15*3600}
local nowTime = os.time()
local time_info = os.date("*t", nowTime)

-- 从星期天0点开始到现在到时间跨度 current_week_time
--- **`wday`** (weekday, 1–7, Sunday is 1)
local weekday = os.date("*t", nowTime).wday - 1
local current_week_time = weekday * 24 * 3600 + time_info.hour * 3600 + time_info.min * 60 + time_info.sec

local find = false
for i = 1, #refresh_list do
    if current_week_time < refresh_list[i] then
        find = i
        break
    end
end

local nextRefreshTime = 0
if find then
    nextRefreshTime = nowTime - current_week_time + refresh_list[find]
else
	-- 如果没有找到则表示是下周刷新
    nextRefreshTime = nowTime - current_week_time + 7*24*3600 + refresh_list[1]
en

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值