拥抱Kubernetes,再见了,SpringBoot cronjob

项目开发中总是需要执行一些定时任务,比如定时处理数据之后发送邮件,定时更新缓存等等。

Java定时任务

  1. 基于 java.util.Timer 定时器,实现类似闹钟的定时任务
  2. 使用 Quartz、elastic-job、xxl-job 等开源第三方定时任务框架,适合分布式项目应用
  3. 使用 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
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值