项目开发中总是需要执行一些定时任务,比如定时处理数据之后发送邮件,定时更新缓存等等。
Java定时任务
-
基于 java.util.Timer 定时器,实现类似闹钟的定时任务 -
使用 Quartz、elastic-job、xxl-job 等开源第三方定时任务框架,适合分布式项目应用 -
使用 Spring 提供的一个注解: @Schedule
项目框架使用的是SpringBoot,所以之前定时任务使用的是SpringBoot中的@Scheduled。可是这种方式并不适合我们现在的cloud环境,为了更加cloud native一点,我删除了使用SpringBoot写的37个定时任务,改为使用Kubernetes cronjob的方式。
定时任务代码编写
public interface Command {
/**
* 遵循Unix约定,如果命令执行正常,则返回0;否则为非0。
*/
int execute(String... args);
}
首先定义一个接口,所有具体的定时任务都必须实现该接口。接下来是具体的某一个定时任务
@Component
@Slf4j
public class ProjectCommandLineRunner implements CommandLineRunner {
Map<String, Command> commandMap = new HashMap<>();
@Autowired
private SendEmailCommand sendEmailCommand;
@PostConstruct
private void init() {
commandMap.put("sendEmail", sendEmailCommand);
}
@Override
public void run(String... args) throws Exception {
if (args.length == 0) {
return;
}
if (!commandMap.containsKey(args[0])) {
log.error("'{}' command not found", args[0]);
System.exit(-1);
}
Command command = commandMap