zoukankan      html  css  js  c++  java
  • springboot实现定时任务的两种方式

     方式一:在springboot启动类上添加@EnableScheduling注解,然后创建具体的任务类,在方法上添加@Scheduled注解,并指明执行频率即可。如下:

    @Component
    public class TestJob {

    private final Logger logger = LoggerFactory.getLogger(TestJob.class);

    @Scheduled(cron = "*/3 * * * * *")
    public void testJob() {
    logger.info("Job Test...");
    }
    }

    方式二:创建一个继承了QuartzJobBean的任务类,同时创建quarz配置类,以向spring容器中注入JobDetail和Trigger。如下:
    public class Test2Job extends QuartzJobBean {

    private final Logger logger = LoggerFactory.getLogger(Test2Job.class);
    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
    logger.info("Test2 Job...");
    }
    }
    @Configuration
    public class ScheculerConfiguration {

    @Bean
    public JobDetail jobDetail() {
    return JobBuilder.newJob(Test2Job.class)
    .withIdentity("test2Job")
    .storeDurably()
    .build();
    }

    @Bean
    public Trigger jobTrigger() {
    ScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
    .withIntervalInMilliseconds(3)
    .repeatForever();
    return TriggerBuilder.newTrigger()
    .withIdentity("test2JobTrigger")
    .forJob(jobDetail())
    .withSchedule(scheduleBuilder)
    .build();
    }
    }
  • 相关阅读:
    EditText之边框颜色
    Android之drawable state各个属性详解
    Android-第三天
    Android 问题
    ios VS android
    Android-第二天(2)
    collapse
    2020/3/7
    2020/3/6
    P3825 [NOI2017]游戏
  • 原文地址:https://www.cnblogs.com/gujianzhe/p/10053512.html
Copyright © 2011-2022 走看看