Spring计划任务(定时任务)

本文介绍了Spring 3.1及以上版本中的计划任务配置,通过启用@EnableScheduling注解来支持定时任务,并展示了如何使用@Scheduled注解声明任务。支持的调度类型包括cron、fixedDelay和fixedRate。文中通过示例代码详细演示了计划任务的创建和运行过程。

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

适用于Sping3.1以后的版本,首先通过注解@EnableScheduling开启对计划任务的支持,然后在计划任务的方法上添加注解@Scheduled来申明这是一个计划任务。

Spring通过@Scheduled支持多种类型的计划任务,包含cron,fixDelay,fixRate等


demo~

1.计划任务执行类

package com.xjj.task;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * SpringBoot
 * Created by xian.juanjuan on 2017-6-12 14:02.
 */
@Service
public class ScheduledTaskService {
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:hh:ss");

    @Scheduled(fixedDelay = 2000)
    public void runFixedRateTime(){
        System.out.println("每隔两秒执行一次"+dateFormat.format(new Date()));
    }

    @Scheduled(cron = "0 2 14 ? * *")//每天14点12分执行,cron是Linux和Unix系统下的定时任务
    public void runCron(){
       System.out.println("在指定时间执行"+dateFormat.format(new Date()));
    }
}

2.配置类

package com.xjj.task;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

/**
 * SpringBoot
 * Created by xian.juanjuan on 2017-6-12 14:08.
 */
@Configuration
@ComponentScan("com.xjj.task")
@EnableScheduling
public class ScheduledConfig {

}

3.运行

package com.xjj.task;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * SpringBoot
 * Created by xian.juanjuan on 2017-6-12 14:09.
 */
public class Main {
    public static void main(String[] args){
        new AnnotationConfigApplicationContext(ScheduledConfig.class);
    }
}
结果



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值