4

java定时任务的两种原生实现方式.

 2 years ago
source link: http://www.hechunbo.com/index.php/archives/406.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

java定时任务

Spring Boot提供了@EnableScheduling和@Scheduled注解,用于支持定时任务的执行

方法一:利用scheduled注解

启动类加上@EnableScheduling, 这个注解内部@Import(SchedulingConfiguration.class) 引用了 SchedulingConfiguration类

@SpringBootApplication
@EnableScheduling  
@Configuration
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
        }
    }
//注意在类上加@Component注解,标注这个类为Spring容器的Bean

@Component
public class Task {
    @Scheduled(initialDelay = 1000, fixedRate = 10000)
    public void run() {
        System.out.println("Current time is :: " + Calendar.getInstance().getTime());
    }
}

方法二:重写configureTasks方法

类要继承SchedulingConfigurer

@Component
public class ConfigTask implements SchedulingConfigurer {
    //时间表达式  每2秒执行一次
    private String cron = "0/2 * * * * ?";
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(new Runnable() {
            @Override
            public void run() {
                System.out.println("当前时间为:" + sdf.format(new Date()));
            }
        }, new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                CronTrigger cronTrigger = new CronTrigger(cron);
                Date nextExecDate = cronTrigger.nextExecutionTime(triggerContext);
                return nextExecDate;
            }
        });
    }

    public void setCron(String cron) {
        this.cron = cron;
    }
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK