java定时任务

1、静态定时任务

@Configuration      //1.主要用于标记配置类,兼备Component的效果。
//@Component
@EnableScheduling   // 2.开启定时任务
public class StaticTimedTask {
    //3.添加定时任务
    //指定执行时间
    //@Scheduled(cron = "0/5 * * * * ?")
    //或指定执行时间间隔,例如:5秒
	//@Scheduled(fixedRate=5000)
    public void configureTasks() {
       System.err.println("执行静态定时任务时间: " + LocalDateTime.now());
    }
}

2、基于spring的动态定时任务

在这里插入图片描述
controller

@RestController
@Api(description = "定时任务")
@RequestMapping("/schedule")
public class ScheduleController {
    // 可利用线程存储器对多个定时任务进行管理
	public static ConcurrentHashMap<String, ScheduledFuture> map = new ConcurrentHashMap<String, ScheduledFuture>();
    @Autowired
    private ConfigurationContent youXinConfiguration;
 
    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;
 
    private ScheduledFuture<?> future;
    //创建线程
    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        ThreadPoolTaskScheduler executor = new ThreadPoolTaskScheduler();
        executor.setPoolSize(20);
		executor.setThreadNamePrefix("taskExecutor-");
		executor.setWaitForTasksToCompleteOnShutdown(true);
		executor.setAwaitTerminationSeconds(60);
		return executor;
    }
    @PostMapping("/startTask")
    @ApiOperation("手动执行开始定时任务")
    public String startTask() {
        future = threadPoolTaskScheduler.schedule(new RunnableContent(),new Trigger(){
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext){
                return new CronTrigger(youXinConfiguration.getTaskTime()).nextExecutionTime(triggerContext);//测试时间
//            	return new CronTrigger(youXinConfiguration.getDay()).nextExecutionTime(triggerContext);
            }
        });
        System.out.println("START!!!!!!!!!!");
        return "success start";
 
    }
    @PostMapping("/stopTask")
    @ApiOperation("手动执行关闭定时任务")
    public String stopTask() {
        if (future != null) {
            future.cancel(true);
        }
        return "success stop";
    }
}

ApplicationContextUtil

@Component
public class ApplicationContextUtil implements ApplicationContextAware {
	/**
     * 上下文对象实例
     */
    private static ApplicationContext applicationContext;
  
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
  
    /**
     * 获取applicationContext
     */
    public void setApplicationContext(ApplicationContext applicationContext) {
        ApplicationContextUtil.applicationContext = applicationContext;
    }
    /**
     * 通过name获取 Bean.
     */
    public static Object getBean(String beanName) {
        return applicationContext.getBean(beanName);
    }
    /**
     * 通过class获取Bean.
     */
    public static <T>T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }
}

ConfigurationContent

@Data
@Component
@ConfigurationProperties(prefix = "executionTime")//获取yml配置
@EqualsAndHashCode(callSuper = false)
public class ConfigurationContent {
    private String taskTime;//10s执行一次
//    private String day;//一天执行一次
}

此处的时间需要同时再配置文件中配置,否则启动直接报错

executionTime:
  taskTime: 0/15 * * * * ? #10s
  day: 0 0 4 * * ? #每天4点触发方法   

RunnableContent

public class RunnableContent implements Runnable {
    @Override
    public void run() {
		//通过名字获取实例,同时需要在实例处加注释 *@Service("projectService")*
		//ProjectServiceImpl projectService = (ProjectServiceImpl)ApplicationContextUtil.getBean("projectService");
		//通过类名获取实例
    	ProjectService projectService = (ProjectService)ApplicationContextUtil.getBean(ProjectService.class);
    	Map<String,Object> map = projectService.test();
    	System.out.println(map);
    }
}

StartService

//继承Application接口后项目启动时会按照执行顺序执行run方法通过设置Order的value来指定执行的顺序
@Component
@Order(value = 1)
public class StartService implements ApplicationRunner{

	@Autowired
	private ScheduleController scheduleController;
	@Override
	public void run(ApplicationArguments args) throws Exception {
	    //启动定时任务
		scheduleController.startTask();
	}

}

3、基于接口SchedulingConfigurer的动态定时任务

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值