【Java】使用Timer实现的定时任务,支持按规则执行。

重要声明:本文章仅仅代表了作者个人对此观点的理解和表述。读者请查阅时持自己的意见进行讨论。

本文原地址:https://www.microanswer.cn/blog/32

一、需求

在业务开发中常常出现将结果回调给对接渠道的需求,而回调为了保证成功,通常都会有一个失败重试的功能,这样就需要有一个重试规则,并有一个比较好的机制来处理,而又不关心任务是否可控。

二、实现

根据这样一个需求,可以使用Java提供的Timer来实现,下面是代码。

/**
 * 按rule指定的规则执行 fun 方法<br>
 * 规则的指定: "0 60 120 200"<br>
 *      含义:立刻执行一次方法,待60秒执行一次,再待120秒执行,依次推类,单位始终为秒。<br>
 *      若某一次执行后,后续不希望再执行,d0 方法请返回 true;<br>
 * @param fun  要执行的方法。
 * @param rule 规则。
 */
public static void runWithRule(final Fun fun, String rule) {
    final String[] times = rule.split(" ");

    final Timer timer = new Timer();
    final int[] timeIndex = {0};

    timer.schedule(
            newTimerTask(fun, timeIndex, times, timer),
            Integer.parseInt(times[timeIndex[0]]) * 1000
    );

}
private static TimerTask newTimerTask(
        final Fun fun,
        final int []timeIndex,
        final String[] times,final Timer timer
) {
    return new TimerTask() {
        @Override
        public void run() {
            boolean success = fun.d0();

            // 返回值是 false, 表示后续要继续执行。
            if (!success) {

                // 已经执行完了所有规则。
                if (timeIndex[0] >= (times.length - 1)) {

                    timer.cancel();
                    return;
                }

                timeIndex[0]++;
                timer.schedule(
                        newTimerTask(fun, timeIndex, times, timer),
                        Integer.parseInt(times[timeIndex[0]]) * 1000
                );
            } else {
                // 返回值是true, 不用再执行了。
            }
        }
    };
}
public interface Fun{
    boolean d0();
}

其中分出了一个私有方法,每次timer进行任务注入是,都是使用new的新的TimerTask,TimerTask不能重用,因此提取一个方法出来作为创建TimerTask的私有方法。

三、使用

现在,只需要使用暴露的 runWithRule 即可完成对应功能:

public static void main(String[] args) {
    // 打印程序开始时间,方便对比
    System.out.println(new Date());

    // 调用工具方法
    runWithRule(new Fun() {
        @Override
        public boolean d0() {
            System.out.println(new Date());
            return false;
        }
    }, "1 5 5 10");
}

输出结果:

Tue Sep 03 10:32:03 CST 2019 // 这是第一行打印的程序开始时间。
Tue Sep 03 10:32:04 CST 2019 // 过1秒,执行任务了,与规则符合。
Tue Sep 03 10:32:09 CST 2019 // 过5秒执行,与规则符合。
Tue Sep 03 10:32:14 CST 2019 // 过5秒执行,符合。
Tue Sep 03 10:32:24 CST 2019 // 过10秒执行,符合。

yeah!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: Java通过使用注解来实现定时任务。下面是一个简单的示例: 1. 引入依赖: ``` <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>5.3.3</version> </dependency> ``` 2. 创建定时任务类: ```java import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class MyTask { @Scheduled(cron = "0 0/1 * * * ?") public void run() { // 执行定时任务 } } ``` 3. 在启动类中加入注解 @EnableScheduling ```java import org.springframework.scheduling.annotation.EnableScheduling; @EnableScheduling @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 这样就可以在每分钟执行一次 run() 方法了。 注意: 上面的例子是基于Spring框架的实现。如果没有使用Spring框架,可以使用Java自带的 TimerTimerTask 类实现定时任务。 ### 回答2: 在Java中,可以使用注解来实现定时任务。下面是一个使用注解实现定时任务的案例: 首先,我们需要引入相关的依赖,如SpringBoot、Quartz等。 ```xml <!-- Spring Boot --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!-- Quartz --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency> ``` 然后,创建一个定时任务的工作类,使用`@Component`注解将其注册为Spring组件。 ```java @Component public class ScheduledTask { @Scheduled(cron = "0/10 * * * * ?") // 每隔10秒执行一次 public void task() { // 定时任务的具体逻辑 System.out.println("定时任务执行了"); } } ``` 注解`@Scheduled`用于表示该方法是一个定时任务方法,`cron`属性用于指定定时任务执行时间。例如上述代码中的`cron = "0/10 * * * * ?"`表示每隔10秒执行一次。 最后,在Spring Boot的启动类上添加`@EnableScheduling`注解,启用定时任务的功能。 ```java @SpringBootApplication @EnableScheduling public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 通过以上步骤,我们就可以使用注解实现定时任务。每隔10秒,定时任务就会执行一次,输出"定时任务执行了"。当然,你可以根据自己的需要,调整定时任务的时间设置,以满足不同的业务需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Microanswer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值