Java实现定时器的几种方法

目录

方法1:使用Timer和和TimerTask类

方法2:使用线程池

方法3:使用Spring Task

方法4:通过quartz任务调度工具


Java实现定时器的方法有很多,本章主要浅谈一下知道的几种方法:

方法1:使用Timer和和TimerTask类

1、Timer和TimerTask是java.util包下的类,用于实现定时任务

步骤1:创建TimerTask定时器任务,可以通过匿名内部类的方式创建

步骤2:创建Timer定时器,调用定时器的方法执行定时器任务

2、Timer的两个方法schedule()和scheduleAtFixedRate()及其重载方法:

void schedule(TimerTask task, long delay):在指定时间后执行1次任务,其中delay表示时延,单位是毫秒,设置为1000,则表示1秒后执行一次定时器任务;

void schedule(TimerTask task, long delay, long period):指定延迟指定时间后周期性地执行任务(delay毫秒后,每period毫秒执行一次)

void scheduleAtFixedRate(TimerTask task, long delay, long period):指定延迟指定时间后周期性地执行任务(delay毫秒后,每period毫秒执行一次)

void scheduleAtFixedRate(TimerTask task, Date firstTime,long period) :从指定日期firstTime开始,每period毫秒执行一次任务

3、案例代码

public class TimerExample {
    public static void main(String[] args) {
        // 创建定时器
        Timer timer = new Timer();
        // 创建定时器任务
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                System.out.println("Hello world!");
            }
        };

        timer.schedule(timerTask, 1000); // 1秒后执行一次
        timer.schedule(timerTask, 2000, 2000); // 两秒后每两秒执行一次
        timer.scheduleAtFixedRate(timerTask, 3000, 3000); // 3秒后每3秒执行一次
        timer.scheduleAtFixedRate(task, new Date(), 4000); // 每4秒执行一次
    }

}

方法2:使用线程池

其中线程池的方法使用和Timer一样,TimeUnit是一个枚举类型,用于指定时间单位,有NANOSECONDS(纳秒)、MICROSECONDS(微秒)、MILISECONDS(毫秒)、SECONDS(秒)、MINUTE(分钟)、HOURS(小时)和DAYS(天)。

案例代码:

public class TimerExample {
    public static void main(String[] args) {
        // 创建定时器任务
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                System.out.println("Hello world!");
            }
        };

        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(2);

        scheduledThreadPool.schedule(timerTask, 1000, TimeUnit.MILLISECONDS);
        scheduledThreadPool.scheduleAtFixedRate(timerTask, 1000, 1000, TimeUnit.MILLISECONDS);
    }

}

方法3:使用Spring Task

步骤1:在springBoot启动类上添加@EnableScheduling注解

@EnableScheduling
@SpringBootApplication
public class SpringbootApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootApplication.class, args);
    }

}

步骤2:创建一个定时任务类的bean,在类的方法上使用@Schedule注解,通过注解的cron属性设置定时器的属性

@Component
public class TimerTask {
    @Scheduled(cron = "0 7 2 26 7 *")
    public void task() {
        System.out.println("定时任务...");
    }

}

以上代码指定在2022年7月26日02:07:00执行一次定时任务,对cron表达式感兴趣的可以去学习了解一下,这里就不介绍了。

方法4:通过Quartz任务调度工具

步骤1:在pom.xml中添加quartz的依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-quartz</artifactId>
</dependency>

步骤2:创建quartz的配置类

@Configuration
public class QuartzConfig {
    // 创建一个JobDetail(工作详情)类对象,保存到Spring容器中,这个类用于封装我们编写的job接口实现类
    @Bean
    public JobDetail jobDetail(){
        System.out.println("showTime方法运行");
        return JobBuilder.newJob(QuartzJob.class)   // 绑定要运行的任务类的类对象
                .withIdentity("job")               // 设置job的名称
                .storeDurably()                     // 信息持久
                // 设置storeDurably之后,当没有触发器指向这个JobDetail时,JobDetail也不会从
                // Spring容器中删除,如果不设置这行,就会自动从Spring容器中删除
                .build();
    }

    // 声明触发器,触发器决定我们的工作\任务何时触发
    @Bean
    public Trigger trigger(){
        System.out.println("showTime触发器运行");

        // 定义Cron表达式,每分钟触发一次
        CronScheduleBuilder cronScheduleBuilder = 
                CronScheduleBuilder.cronSchedule("0/10 * * * * ?");
        
        return TriggerBuilder.newTrigger()
                .forJob(jobDetail()) // 绑定JobDetail对象
                .withIdentity("trigger") // 定义触发器名称
                .withSchedule(cronScheduleBuilder) // 绑定Cron表达式
                .build();
    }

}

步骤:3:定义Job

public class QuartzJob implements Job {
    @Override
    public void execute(JobExecutionContext jobExecutionContext) {
        // 输出当前时间
        System.out.println(LocalDateTime.now());
    }
}

猜你喜欢

转载自blog.csdn.net/heyl163_/article/details/126262983