Java实现执行任务调度(定时执行某个方法)

做数据同步的时候,整理这么几个定时方法,可以借鉴

第一种:

jdk提供的定时器工具Timer 

1.单线程

2.可以指定延迟(开始执行的时间)、周期时间

3.可以调度指定的的需要执行的任务

/**
 *  Timer也可以指定具体时间执行
 *  String time = "2019-07-02 12:00:00"; 
 *  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
 *  Date delay = sdf.parse(time);//执行时间
 *  timer.scheduleAtFixedRate(执行任务, delay, 周期);
 */
public void Ds01()  {
    // 需要定时执行的任务
    TimerTask task = new TimerTask() {
        public void run() {
            System.out.println("-----定时测试-----");
        }
    };
    // Timer定时器工具
    Timer timer = new Timer();
    // 延迟(首次执行的时间)
    long delay = 0;
    // 间隔周期(/毫秒数)
    long intevalPeriod = 5 * 1000;
    立即执行,并且每5秒执行一次
    timer.scheduleAtFixedRate(task, delay, intevalPeriod);
}

第二种:最理想的定时器

1.通过线程池的方式来执行任务

2.可以设定时间颗粒度
        TimeUnit.DAYS //天        TimeUnit.HOURS  //小时        TimeUnit.MINUTES //分钟  
        TimeUnit.SECONDS //秒        TimeUnit.MILLISECONDS //毫秒        TimeUnit.NANOSECONDS //毫微秒                            TimeUnit.MICROSECONDS //微秒

/**
 * ses.scheduleAtFixedRate(执行任务, 延迟(首次执行的时间), 周期, 延迟/周期的单位);
 */
public void Ds02() {
	// 需要定时执行的任务
	Runnable runnable = new Runnable() {
		public void run() {
			System.out.println("-----定时器-----");
		}
	};
	ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
    //立即执行,并且每5秒执行一次
	ses.scheduleAtFixedRate(runnable, 0, 5000, TimeUnit.MILLISECONDS);
}

第三种:SpringBoot项目中的定时器 (SpringBoot中的任务调度)

1.方便,快速

1.在boot的启动类(主入口)的类上添加注解@EnableScheduling,加上注解以后,项目会自动添加对应的配置文件

2.在需要使用任务调度的类上面加注解 @Component,使该类被Spring管理

import org.springframework.stereotype.Component;

@Component
public class Ds {
    //方法1 {...}
    //方法2 {...}
    //....
}

3.任务调度的方法上面加注解 @Scheduled

1) cron属性:时间表达式

2) fixedRate属性:上一个调用开始后再次调用的延时(再次调用时不需要等上一个调用执行完成)

3) fixedDelay属性:上一个调用完成后再次调用的延时(再次调用时需要等上一个调用执行完成)

4) initialDelay属性:第一次调用时的延迟时间

属性含义
fixedRate = 1000每秒执行一次,单位毫秒
"0 0 10,14,16 * * ?"每天10点、14点、16点 触发
"0 0/30 9-17 * * ?"朝九晚五工作时间内每半小时触发
"0 0 12 ? * WED"表示每个星期三中午12点触发
"0 0 12 * * ?"每天中午12点触发
"0 15 10 ? * *"每天上午10:15触发
"0 15 10 * * ?"每天上午10:15触发
"0 15 10 * * ? *"每天上午10:15触发
"0 15 10 * * ? 2005"2005年的每天上午10:15触发
"0 * 14 * * ?"在每天下午2点到下午2:59期间的每1分钟触发
"0 0/5 14 * * ?"在每天下午2点到下午2:55期间的每5分钟触发
"0 0/5 14,18 * * ?"在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发
"0 0-5 14 * * ?"在每天下午2点到下午2:05期间的每1分钟触发
"0 10,44 14 ? 3 WED"每年三月的星期三的下午2:10和2:44触发
"0 15 10 ? * MON-FRI"周一至周五的上午10:15触发
"0 15 10 15 * ?"每月15日上午10:15触发
"0 15 10 L * ?"每月最后一日的上午10:15触发
"0 15 10 ? * 6L"每月的最后一个星期五上午10:15触发
"0 15 10 ? * 6L 2002-2005"2002年至2005年的每月的最后一个星期五上午10:15触发
"0 15 10 ? * 6#3"每月的第三个星期五上午10:15触发
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class Ds {

	//每1秒执行一次该方法
	@Scheduled(fixedRate = 1000)
	public void test() {
		System.out.println("------定时调度------");
	}
	
	//每天12点执行一次该方法
	@Scheduled("0 0 12 * * ?")
	public void test2() {
		System.out.println("------定时调度2------");
	}
	
}

通常情况下,任务调度需要配合异步功能,所以类只需要再添加一个注解@EnableAsync

import org.springframework.stereotype.Component;
import org.springframework.scheduling.annotation.EnableAsync;

@Component
@EnableAsync
public class Ds {

	//每1秒执行一次该方法
	@Scheduled(fixedRate = 1000)
	public void test() {
		System.out.println("------定时调度------");
	}
	
	//每天12点执行一次该方法
	@Scheduled("0 0 12 * * ?")
	public void test2() {
		System.out.println("------定时调度2------");
	}
	
}

SpringBoot注解 番外篇

在这里,我重点解释下这个注解方式

如果直接把@EnableScheduling注解写到启动类中,这样的话就会很死板

所以得想个办法

不在启动类中加注解,而是通过配置文件 能人为控制定时任务的开启或关闭

进入@EnableScheduling,看到引入的 SchedulingConfiguration.class ,进去后不难发现,该类注入了ScheduledAnnotationBeanPostProcessor 

知道了上面这些,所以现在我们需要做的就是通过配置来控制定时任务

手动编写一个配置类来控制(不需要方法),如下:

import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.scheduling.annotation.SchedulingConfiguration;

@Configuration
@ConditionalOnExpression(value = "${task.scheduling}")
@Import(SchedulingConfiguration.class)
public class TaskEnableSchedulingConfig {

}

application.yml 添加个配置,通过true|false来控制 TaskEnableSchedulingConfig 这个类

# 定时任务开启状态
task:
  scheduling: true

这样,就能通过application.yml配置文件来控制是否要开启定时任务了

  • 13
    点赞
  • 56
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 8
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

学弟不想努力了

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值