栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据

springboot实现定时器的3种方法

大数据 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot实现定时器的3种方法

springboot实现定时器
       ## 1.基于注解  @Scheduled
       ## 2.基于接口 SchedulingConfigurer
       ## 基于多线程

基于注解的方式 @Scheduled

package com.kusen.mq.rabbitmq.task;

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

import java.time.LocalDateTime;




//1.主要用于标记配置类
@Configuration
// 2.开启定时任务
@EnableScheduling
public class ScheduleTask {
    //3.添加定时任务
    @Scheduled(cron = "0/5 * * * * ?")
    //或直接指定时间间隔,例如:5秒
    //@Scheduled(fixedRate=5000)
    private void configureTasks() {
        System.out.println("基于注解(@Scheduled)的简单定时器demo: " + LocalDateTime.now());
    }
}


基于接口方式实现 核心接口:SchedulingConfigurer
定义一个抽象类。实现了SchedulingConfigurer接口 这是方便其他定时任务对其扩展和动态添加

 基于SchedulingConfigurer 实现的父类
package com.kusen.mq.rabbitmq.scheduling;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;


import java.util.concurrent.*;


@Configuration
@EnableScheduling
public abstract class ConfigurerScheduling implements SchedulingConfigurer {
    
    private String schedulerName;

    
    private String cron;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(taskScheduler());
        taskRegistrar.addTriggerTask(() -> {
            if(isWork()){
                processTask();
            }
        }, triggerContext -> {
//            if (StringUtils.isEmpty(cron)) {
//                cron = getCron();
//            }
            cron = getCron();
            return new CronTrigger(cron).nextExecutionTime(triggerContext);
        });
    }

    
    public abstract void processTask();

    
    protected abstract String getCron();

    
    protected abstract Boolean isWork();

    
    @Bean(destroyMethod = "shutdown")
    public Executor taskScheduler() {
        //设置线程名称
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build();
        //创建线程池
        return Executors.newScheduledThreadPool(5, namedThreadFactory);
    }

}

子类实现

package com.kusen.mq.rabbitmq.task;

import com.kusen.mq.rabbitmq.scheduling.ConfigurerScheduling;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;


 //将这个任务交给spring容器管理
@Configuration
public class TaskDemo1 extends ConfigurerScheduling {

    @Override
    public void processTask() {
        System.out.println("基于接口SchedulingConfigurer的动态定时任务 任务性质是每隔5秒从数据库中查询数据:"
                + LocalDateTime.now() + ",线程名称:" + Thread.currentThread().getName()
                + " 线程id:" + Thread.currentThread().getId());
    }

    @Override
    protected String getCron() {
        return "*/5 * * * * ?";
    }
 
    @Override
    protected Boolean isWork() {
        return true;
    }
}

package com.kusen.mq.rabbitmq.task;

import com.kusen.mq.rabbitmq.config.DynamicScheduleTask;
import com.kusen.mq.rabbitmq.scheduling.ConfigurerScheduling;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;


@Configuration
public class TaskDemo4 extends ConfigurerScheduling {
    @Autowired      //注入mapper
    @SuppressWarnings("all")
    DynamicScheduleTask.CronMapper cronMapper;
    private Map cache =new HashMap<>();

    
    @Override
    public void processTask() {
        System.out.println("基于接口SchedulingConfigurer的动态定时任务:时间任务从数据库中动态获取执行获取"
                + LocalDateTime.now() + ",线程名称:" + Thread.currentThread().getName()
                + " 线程id:" + Thread.currentThread().getId());
    }

    
    @Override
    protected String getCron() {
        String cron = cronMapper.getCron();
        return cron;
    }

    @Override
    protected Boolean isWork() {
        return true;
    }
}

基于多线程方式

package com.kusen.mq.rabbitmq.task;

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;


@Component
@EnableScheduling   // 1.开启定时任务
@EnableAsync        // 2.开启多线程
public class MultithreadScheduleTask {
    @Async
    @Scheduled(fixedDelay = 1000)  //间隔1秒
    public void first() throws InterruptedException {
        System.out.println("第一个定时任务开始 : " + LocalDateTime.now().toLocalTime() + "rn线程 : " + Thread.currentThread().getName());
        System.out.println();
        Thread.sleep(1000 * 10);
    }
    @Async
    @Scheduled(fixedDelay = 2000)
    public void second() {
        System.out.println("第二个定时任务开始 : " + LocalDateTime.now().toLocalTime() + "rn线程 : " + Thread.currentThread().getName());
        System.out.println();
    }

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/278232.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号