通过注解实现Spring定时任务实例

本文介绍了如何使用Spring框架配置并实现定时任务。通过在配置类中使用@EnableScheduling注解来启用定时任务支持,并在具体任务方法上使用@Scheduled注解定义执行策略。提供了两个示例方法,分别演示了基于固定间隔和特定时间点的任务执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 首先通过在配置类注解@EnableScheduling 来开启对定时任务的支持,然后在要执行的定时任务方法上注解@Scheduled,声明这是一个定时任务

2. 任务执行类

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.Date;
@Service
public class ScheduledTaskService {
   private static final SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

   @Scheduled(fixedRate = 5000)
   public void fixedRateTime() {
      System.out.println("每隔5秒执行一次:" + sf.format(new Date()));
   }

   @Scheduled(cron = "0 10 16 * * ?")
   public void fixTime() {
      System.out.println("在指定时间 " + sf.format(new Date()) + "执行");
   }
}

代码解释:fixedRate 属性指每隔固定时间执行,cron 属性指按照指定时间执行,本实例指每天16点10分执行任务

3. 配置类

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@EnableScheduling
@ComponentScan("com.xuanwu.scheduled")
public class ScheduledConfig {
}

4. 运行

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
   public static void main(String[] args) {
      AnnotationConfigApplicationContext context = new
            AnnotationConfigApplicationContext(ScheduledConfig.class);
   }
}

 

转载于:https://my.oschina.net/feinik/blog/841723

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值