javaEE颠覆者十一

javaEE颠覆者第三章
3.3 定时任务
从spring3.1开始,定时任务在spring实现变得异常简单。用@EnableScheduling来开启支持,在要执行定时任务的方法上加上注解@Scheduled进行声明
(1)定时任务执行类

package spring4.taskscheduler;

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

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

@Service
//@EnableScheduling  //也可在方法本身开启 与配置类等价
public class ScheduledTaskService {
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    //@Scheduled(fixedRate = 5000) //使用@Scheduled声明该方法是计划(定时)任务   使用fixedRate规定每隔多少时间运行(单位是毫秒)  
    public void reportCurrentTime() {
        System.out.println("每隔五秒执行一次 "+dateFormat.format(new Date()));
    }

    @Scheduled(cron = "00 10 11 ? * *") //使用cron属性按照指定时间执行 本例指的是 每天的11点08分执行一次
    public void fixTimeExecution() {
        System.out.println("在指定时间 "+dateFormat.format(new Date())+" 执行");
    }
}

(2)配置类

package spring4.taskscheduler;

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

@Configuration
@ComponentScan("spring4.taskscheduler")
@EnableScheduling   //开启对计划任务的支持
public class TaskSchedulerConfig {

}

(3)运行

package spring4.taskscheduler;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskSchedulerConfig.class);
        ScheduledTaskService scheduledTaskService = context.getBean(ScheduledTaskService.class);
    }
}

结果
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值