Quartz定时任务使用(一)

一、概述

用Spring,就是为了简单。

但是我还是要总结下java定时任务实现的几种方式。

1.TimerTask,等于一个线程隔一段时间运行一下。

2.ScheduledExecutorService,线程池版的TimerTask。

3.Spring支持的定时任务,@Schedule注解,支持crontab表达式。

4.quartz,比较流行的任务调度工具,就是配置起来麻烦。

这里只讲3、4,前两个跟Spring没关系,这里不讲。

二、内置定时任务

2.1 Maven依赖

内置定时任务不需要额外添加依赖。

2.2 配置文件

在application.properties 中不需要额外添加下面的配置,但是可以把定时任务的crontab表达式提出来,如:

schedule.task.test=0/2 * * * * ?

2.3 配置定时任务

需要使用@EnableScheduling注解启动定时任务,然后在需要定时执行的方法上加上@Scheduled即可:

ScheduleConfig:

package com.cff.springbootwork.schedule.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import com.cff.springbootwork.schedule.service.ScheduleService;

@Configuration
@EnableScheduling
public class ScheduleConfig {
    @Autowired
    ScheduleService scheduleService;

    @Scheduled(cron = "${schedule.task.test}")
    public void dayJob() {
        scheduleService.doJob();
    }
}

2.4 测试的Service

package com.cff.springbootwork.schedule.service;

import org.springframework.stereotype.Service;

@Service
public class ScheduleService {

    public void doJob() {
        System.out.println("test");
    }

}
posted @   黑狗已醒  阅读(763)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示