前端实现定时任务,每天定时更新数据 “ setInterval + new Date()(或moment.js)“

项目场景:

每天定时更新系统数据,前端通过系统时间及setInterval来实现


问题描述

在项目中会遇到一些情况,比如用户不关闭设备,导致设备有时无法同步最新的数据,这里就需要通过特定时间来重新获取最新数据并渲染出来,此时就需要通过定时任务来满足这种需求;


解决方案:

提示:这里通过new Date()计算时间差,通过定时器setInterval来实现指定时间更新数据:

javascript 复制代码
// 切记,登录系统后先跑一下定时任务
timedTask();


/* 定时任务,每天定时获取数据 */
export const timedTask = () => {
  // 获取当前时间
  const now: any = new Date();

  // 这里设置刷新时间为每天固定时间(例如 08:00:00)
  const refreshTime: any = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 8, 0, 0);

  // 计算当前时间距离刷新时间的时间间隔(以毫秒为单位)
  const timeUntilRefresh: any = refreshTime - now;

  // 如果当前时间已经超过刷新时间,则将刷新时间设置为明天的同一时间
  if (timeUntilRefresh < 0) {
    refreshTime.setDate(refreshTime.getDate() + 1);
  }

  // console.log(refreshTime - Date.now(), '定时任务,每天定时获取数据');

  // 设置定时任务,每天固定时间执行刷新数据函数
  const timer = setInterval(() => {
    if ("TODO:需求特定条件") {
    // 时间到处理你的方法
      yourFunction();
       //这里记得清除一下定时器,后面说明原因
      clearInterval(timer);
    }
  }, refreshTime - Date.now());
};




/* 需要处理数据的方法 */
export const yourFunction = () => {
  setTimeout(() => {
    timedTask();
  }, 180000); // 暂定,三分钟后重新开启定时任务
  // ......
  // ......
  // ......
  // 这里处理数据
}

提示:
new Date(year, month, day, hours, minutes, seconds, milliseconds) // 注意:这种方式下,必须传递整型;

各种变量代表的含义是:

month: 用英文 表示月份名称,从January到December ,缩写也行(Jan...Dec);

year: 四位数表示的年份

month: 用整数表示月份,从0(1月)到11(12月)

day: 表示一个月中的第几天,从1到31, defaults to 1.

hours: 小时数,从0(午夜)到23(晚11点), defaults to 0.

minutes: 分钟数,从0到59的整数, defaults to 0.

seconds: 秒数,从0到59的整数, defaults to 0.

milliseconds: 毫秒数,为大于等于0的整数, defaults to 0.

这里也可以使用使用moment插件将日期转换为毫秒数非常简单。可以使用moment().valueOf()方法来获取当前时间的毫秒数,也可以使用moment(日期).valueOf()方法将给定日期转换为毫秒数。

// 假设你有一个不同格式的时间字符串

const timeString = "15-11-2023 16:30:35";

// 使用 moment 解析这个格式的时间字符串,指定格式

const time = moment(timeString, "DD-MM-YYYY HH:mm:ss");

// 然后使用 valueOf 获取这个时间的 Unix 时间戳(毫秒数)

const timestamp = time.valueOf();

console.log(timestamp); // 输出时间的毫秒表示

相关链接:
JavaScript简单倒计时效果的实现

相关推荐
c4fx3 分钟前
Delphi5利用DLL实现窗体的重用
开发语言·delphi·dll
罗_三金3 分钟前
前端框架对比和选择?
javascript·前端框架·vue·react·angular
Redstone Monstrosity10 分钟前
字节二面
前端·面试
东方翱翔17 分钟前
CSS的三种基本选择器
前端·css
鸽芷咕26 分钟前
【Python报错已解决】ModuleNotFoundError: No module named ‘paddle‘
开发语言·python·机器学习·bug·paddle
Jhxbdks36 分钟前
C语言中的一些小知识(二)
c语言·开发语言·笔记
java66666888836 分钟前
如何在Java中实现高效的对象映射:Dozer与MapStruct的比较与优化
java·开发语言
Violet永存36 分钟前
源码分析:LinkedList
java·开发语言
代码雕刻家38 分钟前
数据结构-3.1.栈的基本概念
c语言·开发语言·数据结构
Fan_web40 分钟前
JavaScript高级——闭包应用-自定义js模块
开发语言·前端·javascript·css·html