Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【需求】实现 "定时任务" 模组 #40

Closed
yanqiaoyu opened this issue Apr 11, 2022 · 6 comments · Fixed by #50
Closed

【需求】实现 "定时任务" 模组 #40

yanqiaoyu opened this issue Apr 11, 2022 · 6 comments · Fixed by #50
Assignees
Labels
enhancement New feature or request

Comments

@yanqiaoyu
Copy link
Owner

背景:
最近在某个项目里面, 有这样一个场景: 我们需要随机地,定时地,删除某个文件夹下的一些文件, 以此验证一个自动备份的功能
实现这个随机删除的功能很简单, 但是这个定时执行的功能很尴尬, 最终是用crontab去实现的.
有必要针对这一块拓展一下我的工具盒的功能了

@yanqiaoyu yanqiaoyu added the enhancement New feature or request label Apr 11, 2022
@yanqiaoyu yanqiaoyu self-assigned this Apr 11, 2022
@yanqiaoyu yanqiaoyu changed the title 【需求】任务底下做两个模块,一个手动任务,一个定时任务 【需求】实现 "定时任务" 模组 Apr 15, 2022
@yanqiaoyu
Copy link
Owner Author

初步调研了一下, 准备用 golang 的 cron 实现

@yanqiaoyu
Copy link
Owner Author

再仔细调研了一下, 目前有2个库可供选择
一个是cron
github repo
https://github.com/robfig/cron
go docu
https://pkg.go.dev/github.com/robfig/cron/v3#section-readme

一个是gocron
github repo
https://github.com/jasonlvhit/gocron
go docu
https://pkg.go.dev/github.com/jasonlvhit/gocron#section-readme

其中cron的语法格式贴近linux中的crontab语法, 而gocron支持链式调用, 使用上类似gorm

准备还是用gocron试试

@yanqiaoyu
Copy link
Owner Author

开始进行表单设计, 初步规划做2个页面
1个页面做定时任务本身相关的交互
1个页面做定时任务执行结果相关的交互

找到了一个与我想法类似的开源项目
https://github.com/ntuwang/go_cron

可以参考一下他的model文件里面, 对于表单的设计

@yanqiaoyu
Copy link
Owner Author

尝试使用gocron的途中遇到了以下问题:

  1. 定时任务的时间间隔设置, 采用的是every().XXX()的方法
    但是前端传定时时间过来的时候, 是不确定是隔1秒,还是1分钟,还是1小时的
    这意味着使用gocron我还需要解析一下时间间隔, 然后用一个switch-case来针对性的新建任务

  2. 定时任务模块肯定会有取消定时任务这个功能
    但是我注意到, gocron里面, 新建任务之后, 不会返回这个新建的任务的ID, 只返回err

image

但是, 如果我想要移除某个特定的任务, 却需要知道这个任务的ID, 或者任务函数(我预期我的场景是会出现重复函数的)

image

这就会导致我在现实取消功能的时候非常麻烦

但是cron库这一块就做的比较好了

image

image

image

切换到cron继续尝试

@yanqiaoyu
Copy link
Owner Author

yanqiaoyu commented Apr 28, 2022

cron这个库也有缺陷
比如说我们新增了一个定时任务后, 没有办法立即执行
我看了下这个库的issues和PR,有很多人提到了这个问题, 并且已经有人给出了解决方案,提交了PR
如果作者不合进去, 只能自己手动改这个库的源码了

@yanqiaoyu
Copy link
Owner Author

立即执行实际上不需要改源码,我属实是有点小题大做了...

image

虽然不优雅, 但是能解决问题就完事了嗷

@yanqiaoyu yanqiaoyu linked a pull request May 4, 2022 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant