const{createApp}=Vue const{createVuetify,useGoTo,useDisplay}=Vuetify var data={alert:{show:false,color:'success',text:'',timeout:0,},theme:{dark:false,},nav:{showDrawer:false,showTOC:true,tocPanel:0,tab:'account',post:{discussionId:6821,currentPage:1,targetPage:1,total:4,anchor:0,goToOptions:{container:null,duration:0,easing:'easeInOutCubic',offset:-100,},worker:null,task:[],active:[],apiLock:[],originLike:new Map([]),},related:{block:1,}},search:{width:80,text:null,loading:false,},tags:[{id:20,url:'/t/2c0b5e546a045c756077023a1a1e',name:'Js|Ts|H5',color:'#FFA726',icon:'mdi-language-javascript',},],posts:[{id:84043,num:0,uid:11685,content:'Hey, 我是 沉浸式趣谈本文首发于 [沉浸式趣谈] ,我的个人博客 https://yaolifeng.com 也同步更新。转载请在文章开头注明出处和版权信息。如果本文对您有所帮助,请 点赞、评论、转发,支持一下,谢谢!\u003Cp\u003E说实话,作为前端开发者,我们经常需要处理一些定时任务,比如轮询接口、定时刷新数据、自动登出等功能。\u003C/p\u003E\u003Cp\u003E过去我总是用 \u003Ccode\u003EsetTimeout\u003C/code\u003E 和 \u003Ccode\u003EsetInterval\u003C/code\u003E,但这些方案在复杂场景下并不够灵活。\u003C/p\u003E\u003Cp\u003E我寻找了更可靠的方案,最终发现了 cron 这个 npm 包,为我的前端项目(特别是 Node.js 环境下运行的那部分)带来了专业级的定时任务能力。\u003C/p\u003Ecron 包:不只是个定时器\u003Cp\u003E安装超级简单:\u003C/p\u003E\u003Ccode\u003Enpm install cron\u003C/code\u003E\u003Cp\u003E基础用法也很直观:\u003C/p\u003E\u003Ccode\u003Eimport { CronJob } from \u0026#39;cron\u0026#39;;const job \u003D new CronJob( \u0026#39;0 */30 * * * *\u0026#39;, // 每 30 分钟执行一次 function () { console.log(\u0026#39;刷新用户数据...\u0026#39;); // 这里放刷新数据的代码 }, null, // 完成时的回调 true, // 是否立即启动 \u0026#39;Asia/Shanghai\u0026#39; // 时区);\u003C/code\u003E\u003Cp\u003E看起来挺简单的,对吧?\u003C/p\u003E\u003Cp\u003E但这个小包却能解决前端很多定时任务的痛点。\u003C/p\u003E理解 cron 表达式,这个\u0026#34;魔法公式\u0026#34;\u003Cp\u003E刚开始接触 cron 表达式时,我觉得这简直像某种加密代码。\u003Ccode\u003E* * * * * *\u003C/code\u003E 这六个星号到底代表什么?\u003C/p\u003E\u003Cp\u003E在 npm 的 cron 包中,表达式有六个位置(比传统的 cron 多一个),分别是:\u003C/p\u003E\u003Ccode\u003E秒 分 时 日 月 周\u003C/code\u003E\u003Cp\u003E比如 \u003Ccode\u003E0 0 9 * * 1\u003C/code\u003E 表示每周一早上 9 点整执行。\u003C/p\u003E\u003Cp\u003E我找到一个特别好用的网站 crontab.guru 来验证表达式。\u003C/p\u003E\u003Cp\u003E不过注意,那个网站是 5 位的表达式,少了\u0026#34;秒\u0026#34;这个位置,所以用的时候需要自己在前面加上秒的设置。\u003C/p\u003E\u003Cp\u003E月份和星期几还可以用名称来表示,更直观:\u003C/p\u003E\u003Ccode\u003E// 每周一、三、五的下午 5 点执行const job \u003D new CronJob(\u0026#39;0 0 17 * * mon,wed,fri\u0026#39;, function () { console.log(\u0026#39;工作日提醒\u0026#39;);});\u003C/code\u003E前端开发中的实用场景\u003Cp\u003E作为前端开发者,我在这些场景中发现 cron 特别有用:\u003C/p\u003E1. 在 Next.js/Nuxt.js 等同构应用中刷新数据缓存\u003Ccode\u003E// 每小时刷新一次产品数据缓存const cacheRefreshJob \u003D new CronJob( \u0026#39;0 0 * * * *\u0026#39;, async function () { try { const newData \u003D await fetchProductData(); updateProductCache(newData); console.log(\u0026#39;产品数据缓存已更新\u0026#39;); } catch (error) { console.error(\u0026#39;刷新缓存失败:\u0026#39;, error); } }, null, true, \u0026#39;Asia/Shanghai\u0026#39;);\u003C/code\u003E2. Electron 应用中的定时任务\u003Ccode\u003E// 在 Electron 应用中每 5 分钟同步一次本地数据到云端const syncJob \u003D new CronJob( \u0026#39;0 */5 * * * *\u0026#39;, async function () { if (n**igator.onLine) { // 检查网络连接 try { await syncDataToCloud(); sendNotification(\u0026#39;数据已同步\u0026#39;); } catch (err) { console.error(\u0026#39;同步失败:\u0026#39;, err); } } }, null, true);\u003C/code\u003E3. 定时检查用户会话状态\u003Ccode\u003E// 每分钟检查一次用户活动状态,30 分钟无活动自动登出const sessionCheckJob \u003D new CronJob( \u0026#39;0 * * * * *\u0026#39;, function () { const lastActivity \u003D getLastUserActivity(); const now \u003D new Date().getTime(); if (now - lastActivity \u0026gt; 30 * 60 * 1000) { console.log(\u0026#39;用户 30 分钟无活动,执行自动登出\u0026#39;); logoutUser(); } }, null, true);\u003C/code\u003E踩过的那些坑\u003Cp\u003E使用 cron 包时我踩过几个坑,分享给大家:\u003C/p\u003E时区问题:有次我设置了一个定时提醒功能,但总是提前 8 小时触发。一查才发现是因为没设置时区。所以国内用户一定要设置 \u003Ccode\u003E\u0026#39;Asia/Shanghai\u0026#39;\u003C/code\u003E!\u003Ccode\u003E// 这样才会在中国时区的下午 6 点执行const job \u003D new CronJob(\u0026#39;0 0 18 * * *\u0026#39;, myFunction, null, true, \u0026#39;Asia/Shanghai\u0026#39;);\u003C/code\u003Ethis 指向问题:如果你用箭头函数作为回调,会发现无法访问 CronJob 实例的 this 。\u003Ccode\u003E// 错误示范const job \u003D new CronJob(\u0026#39;* * * * * *\u0026#39;, () \u003D\u0026gt; { console.log(\u0026#39;执行任务\u0026#39;); this.stop(); // 这里的 this 不是 job 实例,会报错!});// 正确做法const job \u003D new CronJob(\u0026#39;* * * * * *\u0026#39;, function () { console.log(\u0026#39;执行任务\u0026#39;); this.stop(); // 这样才能正确访问 job 实例});\u003C/code\u003Ev3 版本变化:如果你从 v2 升级到 v3 ,要注意月份索引从 0-11 变成了 1-12 。实战案例:构建一个智能通知系统\u003Cp\u003E这是我在一个电商前端项目中实现的一个功能,用 cron 来管理各种用户通知:\u003C/p\u003E\u003Ccode\u003Eimport { CronJob } from \u0026#39;cron\u0026#39;;import { getUser, getUserPreferences } from \u0026#39;./api/user\u0026#39;;import { sendNotification } from \u0026#39;./utils/notification\u0026#39;;class NotificationManager { constructor() { this.jobs \u003D []; this.initialize(); } initialize() { // 新品上架提醒 - 每天早上 9 点 this.jobs.push( new CronJob( \u0026#39;0 0 9 * * *\u0026#39;, async () \u003D\u0026gt; { if (!this.shouldSendNotification(\u0026#39;newProducts\u0026#39;)) return; const newProducts \u003D await this.fetchNewProducts(); if (newProducts.length \u0026gt; 0) { sendNotification(\u0026#39;新品上架\u0026#39;, `今天有${newProducts.length}款新品上架啦!`); } }, null, true, \u0026#39;Asia/Shanghai\u0026#39; ) ); // 限时优惠提醒 - 每天中午 12 点和晚上 8 点 this.jobs.push( new CronJob( \u0026#39;0 0 12,20 * * *\u0026#39;, async () \u003D\u0026gt; { if (!this.shouldSendNotification(\u0026#39;promotions\u0026#39;)) return; const promotions \u003D await this.fetchActivePromotions(); if (promotions.length \u0026gt; 0) { sendNotification(\u0026#39;限时优惠\u0026#39;, \u0026#39;有新的限时优惠活动,点击查看详情!\u0026#39;); } }, null, true, \u0026#39;Asia/Shanghai\u0026#39; ) ); // 购物车提醒 - 每周五下午 5 点提醒周末特价 this.jobs.push( new CronJob( \u0026#39;0 0 17 * * 5\u0026#39;, async () \u003D\u0026gt; { if (!this.shouldSendNotification(\u0026#39;cartReminder\u0026#39;)) return; const cartItems \u003D await this.fetchUserCart(); if (cartItems.length \u0026gt; 0) { sendNotification(\u0026#39;周末将至\u0026#39;, \u0026#39;别忘了查看购物车中的商品,周末特价即将开始!\u0026#39;); } }, null, true, \u0026#39;Asia/Shanghai\u0026#39; ) ); console.log(\u0026#39;通知系统已初始化\u0026#39;); } async shouldSendNotification(type) { const user \u003D getUser(); if (!user) return false; const preferences \u003D await getUserPreferences(); return preferences?.[type] \u003D\u003D\u003D true; } // 其他方法... stopAll() { this.jobs.forEach(job \u003D\u0026gt; job.stop()); console.log(\u0026#39;所有通知任务已停止\u0026#39;); }}export const notificationManager \u003D new NotificationManager();\u003C/code\u003E写在最后\u003Cp\u003E作为前端开发者,我们的工作不只是构建漂亮的界面,还需要处理各种复杂的交互和时序逻辑。\u003C/p\u003E\u003Cp\u003Enpm 的 cron 包为我们提供了一种专业而灵活的方式来处理定时任务,特别是在 Node.js 环境下运行的前端应用(如 SSR 框架、Electron 应用等)。\u003C/p\u003E\u003Cp\u003E它让我们能够用简洁的表达式设定复杂的执行计划,帮助我们构建更加智能和用户友好的前端应用。\u003C/p\u003E',ipRegion:'',updatedByUid:0,createdAt:'2025-03-28 12:47:09',updatedAt:'2025-03-29 12:05:41',mentionNum:0,mentionedBy:[],mentionUsers:[],likeUsers:[],},{id:84044,num:1,uid:15254,content:'这个 cron 库看起来 hin 实用',ipRegion:'',updatedByUid:0,createdAt:'2025-03-28 13:57:20',updatedAt:'2025-03-29 12:05:41',mentionNum:0,mentionedBy:[],mentionUsers:[],likeUsers:[],},{id:84045,num:2,uid:6607,content:'我用的是这个,croner',ipRegion:'',updatedByUid:0,createdAt:'2025-03-28 15:31:39',updatedAt:'2025-03-29 12:05:41',mentionNum:0,mentionedBy:[],mentionUsers:[],likeUsers:[],},{id:84046,num:3,uid:15255,content:'如果 node 服务署多个的话,可能要考虑抢占式运行,不了每个服务都运行定时任务有时候会有问题',ipRegion:'',updatedByUid:0,createdAt:'2025-03-28 18:07:21',updatedAt:'2025-03-29 12:05:41',mentionNum:0,mentionedBy:[],mentionUsers:[],likeUsers:[],},],usersMap:new Map([[15255,{uid:15255,url:'/u/290f7a236a045d72626f536f0e19380b',avatar:'/a/290f7a236a045d72626f536f0e19380b',username:'fov6363🤖',}],[15254,{uid:15254,url:'/u/33247e5e6a045d72626f526f38236734',avatar:'/a/33247e5e6a045d72626f526f38236734',username:'hkingstu🤖',}],[6607,{uid:6607,url:'/u/183c7a016a045c71666a516f3e5b3671',avatar:'/a/183c7a016a045c71666a516f3e5b3671',username:'lisxour🤖',}],[11685,{uid:11685,url:'/u/6c7e02096a045d766662536f44060b2e',avatar:'/a/6c7e02096a045d766662536f44060b2e',username:'Lcode01🤖',}],]),related:[{title:'推荐一款自己写的提升效率的浏览器插件: HarmonyAutoCopy,让文本复制更轻松!',url:'/d/6f06033d6a045c77606a567a475c646a1f371708',},{title:'程序猿创业失败,转行做独立开发',url:'/d/393e7d3e6a045c77606a56754350616a59191c16',},{title:'发现一个有意思的项目,把一个字符串隐藏到另一个字符串中',url:'/d/3c117a346a045c77606a56754359676a5b323b0b',},{title:'编程小白,终于成功上线了自己的第一个导航站😭 激动',url:'/d/333944256a045c77606a56754451666a3e0e3e67',},{title:'vue 指令更新问题',url:'/d/2f3c4a3e6a045c77606a5675445e636a250e3f24',},{title:'小红书 | 图文,视频,评论 浏览与导出工具',url:'/d/1b1806556a045c77606a56754458676a04343b26',},{title:'[BadouCMS] Vue3+TypeScript+ThinkPHP8 构建 CMS 系统(开源)',url:'/d/303350036a045c77606a56754458626a20390564',},{title:'开发了一个开箱即用的本地终端 Ztty',url:'/d/0c045a2e6a045c77606a5675455e6b6a3e200734',},{title:'第一个完全用 AI 工具生成的工具站',url:'/d/6a18771a6a045c77606a5675475e616a01126104',},{title:'为什么 vue 的 nuxt.js 不跟进 nextjs 的 app route 目录结构',url:'/d/02116a1e6a045c77606a56744f516a6a1b02141e',},{title:'Vite 开发服务器路径遍历漏洞(CVE-2025-30208)',url:'/d/2f2f0a2b6a045c77606a56744f5a646a231a021b',},{title:'XUGOU - 轻量级系统监控平台,基于 CloudFlare 零成本部署!',url:'/d/0a21430f6a045c77606a56744f58656a0f741e25',},{title:'NextJS 超瓜皮漏洞,赶紧升级!',url:'/d/03226a096a045c77606a56744258646a59126264',},{title:'Typescript 如此成功,为何没有发展出所谓 “Typthon”?',url:'/d/35315c016a045c77606a5674445f626a0e730224',},{title:'为什么 Python 、Node.js 就不能学习一下 C#这种优雅的依赖管理方式?',url:'/d/0f1f5f3d6a045c77606a5674445c676a04311f60',},{title:'求助!双显卡连接 6 个屏幕,展示不同的 URL 页面。Electron 的 displayId 每次重启都会变',url:'/d/1f3158176a045c77606a56744551676a24111b3b',},{title:'关于 react native 和 flutter',url:'/d/6f7c03286a045c77606a56774e50616a27221935',},{title:'[野生程序员花三天时间用 Cursor 复刻经典游戏「俄罗丝方块」,求各位提点建议]',url:'/d/6b047a5e6a045c77606a56774e5c626a2b361d65',},{title:'分享一个用 JS、canvas 写的星空穿越效果',url:'/d/191c61346a045c77606a5677425e6a6a2f28273c',},{title:'郑州招 Python , Node.js 开发岗',url:'/d/082c61146a045c77606a5677425e616a3d706116',},],} const App={setup(){const goTo=useGoTo() const{mdAndUp}=useDisplay() return{goTo,mdAndUp}},data(){return data;},mounted(){const themeDark=localStorage.getItem("themeDark") if(themeDark!==null){this.theme.dark=JSON.parse(themeDark)} if(this.nav.post.total>(this.nav.post.currentPage-1)*100+20){let moreLen=100 if(this.nav.post.total({id:null,num:(this.nav.post.currentPage-1)*100+v,uid:null,content:null,ipRegion:null,updatedByUid:null,createdAt:null,updatedAt:null,mentionNum:null,mentionedBy:null,mentionUsers:null,likeUsers:null,})) this.posts.push(...morePosts.slice(20))} this.workerStart() const hash=window.location.hash const match=hash.match(/#(\d+)/) if(match){const n=parseInt(match[1],10) if(n>=(this.nav.post.currentPage-1)*100&&n{this.jumpTo(n)})}} this.$nextTick(()=>{this.addHeadingIds() tocbot.init({tocSelector:'.toc',contentSelector:'#post-content-0',headingSelector:'h2, h3, h4',headingsOffset:100,scrollSmoothOffset:-100,scrollSmooth:true,collapseDepth:6,onClick:function(e){setTimeout(()=>{history.replaceState(null,'',window.location.pathname+window.location.search)},0)},}) tocbot.refresh()});},beforeUnmount(){this.workerStop() if(this.quill){this.quill.destroy() this.quill=null}},computed:{dposts(){return this.posts.slice(20);},},created(){},methods:{successAlert(msg){this.alert={show:true,color:'success',text:msg,timeout:1500,}},failureAlert(msg){this.alert={show:true,color:'error',text:msg,timeout:5000,}},flipThemeDark(){this.theme.dark=!this.theme.dark localStorage.setItem("themeDark",JSON.stringify(this.theme.dark))},toSearch(){if(!this.search.text){this.failureAlert('搜索词不能为空') return} let keywords=this.search.text.trim() if(keywords.length<1){this.failureAlert('搜索词不能为空') return} if(keywords.length>100){this.failureAlert('搜索词过长') return} this.doSearch(keywords)},toReg(){window.location.href="/reg"},toLogin(){window.location.href="/login"},toPage(){let url=window.location.href url=url.replace(/(\/\d+)?(#[0-9]+)?$/,this.nav.post.targetPage>1?`/${this.nav.post.targetPage}`:'') window.location.href=url},toLoadRelated({done}){if(this.my&&this.my.uid){this.apiLoadRelated({done})}else{done('ok')}},workerStart(){this.nav.post.worker=setInterval(()=>{this.workerLoad()},500);},workerStop(){if(this.nav.post.worker){clearInterval(this.nav.post.worker);this.nav.post.worker=null;}},async jumpTo(num){const page=Math.floor(num/100)+1 const i=num-(page-1)*100 if(page===this.nav.post.currentPage){this.goTo("#post-"+num,this.nav.post.goToOptions) if(!this.posts[i].id){const block=Math.floor(num/20)+1 this.nav.post.apiLock[block]=true await this.apiLoadPosts(block) this.$nextTick(()=>{this.goTo("#post-"+num,this.nav.post.goToOptions)})}}else{let url=window.location.href url=url.replace(/(\/\d+)?(#[0-9]+)?$/,page>1?`/${page}`:'') url=url+"#"+num window.location.href=url}},postIntersect(num){return(isIntersecting,entries,observer)=>{if(isIntersecting){this.nav.post.task.push(num) this.nav.post.active.push(num) this.nav.post.active=this.nav.post.active.filter(item=>Math.abs(item-num)<=5) this.nav.post.active.sort((a,b)=>a-b)}else{this.nav.post.active=this.nav.post.active.filter(item=>item!==num)} if(this.nav.post.active[0]){this.nav.post.anchor=this.nav.post.active[0]}else{this.nav.post.anchor=0}}},async apiLoadPosts(block){try{const response=await axios.post('/fapi/v1/post/block/'+block,{discussionId:this.nav.post.discussionId,}) if(response.data.code===0){response.data.data.posts.forEach(post=>{const i=post.num%100 Object.assign(this.posts[i],post)}) response.data.data.users.forEach(user=>{this.usersMap.set(user.uid,user)})}else{this.failureAlert('回帖数据加载失败: '+response.data.msg)}}catch(error){this.failureAlert('回帖数据加载失败: '+error)} this.nav.post.apiLock[block]=false},workerLoad(){while(this.nav.post.task.length){const num=this.nav.post.task.pop() const i=num-(this.nav.post.currentPage-1)*100 if(!this.posts[i].id){const block=Math.floor(num/20)+1 if(!this.nav.post.apiLock[block]){this.nav.post.apiLock[block]=true this.apiLoadPosts(block)}}}},getTimeInfo(t){if(!t){return ""} const now=new Date();const then=new Date(t);const diff=now-then;const minute=60*1000;const hour=minute*60;const day=hour*24;const month=day*30;const year=month*12;if(diffpost.num===num) if(!post){return "#"+num} const uid=post.uid const username=this.usersMap.get(uid)?.username if(!username){return "#"+num} return username},getUsernameByPostId(id){const post=this.posts.find(post=>post.id===id) if(!post){return "#"+this.getPostNumByPostId(id)} const uid=post.uid const username=this.usersMap.get(uid).username if(!username){return "#"+this.getPostNumByPostId(id)} return username},getPostNumByPostId(id){const post=this.posts.find(post=>post.id===id) return post.num},getPostById(id){const post=this.posts.find(post=>post.id===id) return post},getPostByNum(num){const post=this.posts.find(post=>post.num===num) return post},getAvatarByUid(uid){const avatar=this.usersMap.get(uid)?.avatar if(!avatar){return this.getRandomAvatar()} return avatar},getAvatarByPostNum(num){const post=this.posts.find(post=>post.num===num) if(!post){return this.getRandomAvatar()} const uid=post.uid return this.getAvatarByUid(uid)},getRandomAvatar(){const num=Math.floor(Math.random()*100) return "https://randomuser.me/api/portraits/men/"+num+".jpg"},getUrlByUid(uid){const url=this.usersMap.get(uid)?.url if(!url){return ""} return url},getTextByPostNum(num){const post=this.posts.find(post=>post.num===num) if(!post||!post.content){return '点击跳转到#'+num+'查看'} const parser=new DOMParser() const doc=parser.parseFromString(post.content,'text/html') const text=doc.body.textContent||'' return text.slice(0,100)},addHeadingIds(){const content=document.getElementById('post-content-0') if(!content){this.nav.showTOC=false return} const headings=content.querySelectorAll('h2, h3, h4') headings.forEach((heading,index)=>{if(!heading.id){heading.id=`toc-nav-${index}`}}) if(headings.length==0){this.nav.showTOC=false}},async doSearch(keywords){this.search.loading=true try{const response=await axios.post('/fapi/v1/search',{keywords:keywords,}) if(response.data.code===0){if(response.data.data.hash&&response.data.data.hash.length===32){window.location.href="/s/"+response.data.data.hash}else{this.failureAlert('搜索失败: 搜索服务异常')}}else{this.failureAlert('搜索失败: '+response.data.msg)}}catch(error){this.failureAlert('搜索失败: '+error)} this.search.loading=false},debounce(fn,delay){let timer=null return function(...args){if(timer)clearTimeout(timer) timer=setTimeout(()=>{fn.apply(this,args)},delay);};},},watch:{'nav.post.targetPage':{handler:async function(newV,oldV){this.toPage()},immediate:false},},} const vuetify=createVuetify({defaults:{global:{ripple:true,},},}) const app=createApp(App) app.use(vuetify).mount("#app")