java调度方法记录

编程入门 行业动态 更新时间:2024-10-17 20:20:09

java调度<a href=https://www.elefans.com/category/jswz/34/1771314.html style=方法记录"/>

java调度方法记录

背景

在日常开发中,某些方法需要定时的调度执行,比如执行某个函数,每小时拉取一次数据到数据库;或者每小时需要读取redis中配置信息到内存中等等

方法一 spring @Scheduled

引入包:

import org.springframework.scheduling.annotation.Scheduled;

注解官方解释翻译:

An annotation that marks a method to be scheduled. Exactly one of the cron(), fixedDelay(), or fixedRate() attributes must be specified.
The annotated method must expect no arguments. It will typically have a void return type; if not, the returned value will be ignored when called through the scheduler.
Processing of @Scheduled annotations is performed by registering a ScheduledAnnotationBeanPostProcessor. This can be done manually or, more conveniently, through the <task:annotation-driven/> element or @EnableScheduling annotation.
This annotation may be used as a meta-annotation to create custom composed annotations with attribute overrides.
Since:
3.0
See Also:
EnableScheduling, ScheduledAnnotationBeanPostProcessor, Schedules
Author:
Mark Fisher, Juergen Hoeller, Dave Syer, Chris Beams

该注解用于标记要调度的方法。必须指定cron() 、 fixedDelay()或fixedRate()属性之一。
带注释的方法必须没有参数。 它通常有一个void返回类型; 如果没有,则通过调度程序调用时将忽略返回值。
@Scheduled注解的处理是通过注册一个ScheduledAnnotationBeanPostProcessor来执行的。 这可以手动完成,或者更方便的是,通过<task:annotation-driven/>元素或者在启动函数加上@EnableScheduling注释。

简单的讲:
1.需要调度的函数加上@Scheduled
2.@Scheduled注解中指定调度策略,比如 @Scheduled(cron = “0 0/10 * * * ?”)
3.在启动函数main函数上@EnableScheduling
即可。

方法二:ScheduledExecutorService

引入包:

import java.util.concurrent.ScheduledExecutorService;

官方解释翻译:


An ExecutorService that can schedule commands to run after a given delay, or to execute periodically.
The schedule methods create tasks with various delays and return a task object that can be used to cancel or check execution. The scheduleAtFixedRate and scheduleWithFixedDelay methods create and execute tasks that run periodically until cancelled.Commands submitted using the Executor.execute(Runnable) and ExecutorService submit methods are scheduled with a requested delay of zero. Zero and negative delays (but not periods) are also allowed in schedule methods, and are treated as requests for immediate execution.All schedule methods accept relative delays and periods as arguments, not absolute times or dates. It is a simple matter to transform an absolute time represented as a java.util.Date to the required form. For example, to schedule at a certain future date, you can use: schedule(task, date.getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS). Beware however that expiration of a relative delay need not coincide with the current Date at which the task is enabled due to network time synchronization protocols, clock drift, or other factors.The Executors class provides convenient factory methods for the ScheduledExecutorService implementations provided in this package.

一个ExecutorService可以安排命令在给定的延迟后运行,或定期执行。
schedule方法创建具有各种延迟的任务并返回可用于取消或检查执行的任务对象。 scheduleAtFixedRate和scheduleWithFixedDelay方法创建和执行定期运行直到被取消的任务。
使用Executor.execute(Runnable)和ExecutorService submit方法提交的命令的调度请求延迟为零。 在schedule方法中也允许零延迟和负延迟(但不是周期),并被视为立即执行的请求。
所有schedule方法都接受相对延迟和时间段作为参数,而不是绝对时间或日期。 将表示为java.util.Date的绝对时间转换为所需的形式是一件简单的事情。 例如,要安排在某个未来date ,您可以使用: schedule(task, date.getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS) 。 但是请注意,由于网络时间同步协议、时钟漂移或其他因素,相对延迟的到期不必与启用任务的当前Date一致。
Executors类为此包中提供的 ScheduledExecutorService 实现提供了方便的工厂方法。

实践样例
demo: 从redis中定期更新配置信息

    public void  RedisTime(String key, HashSet<String> blackList, String host, String port, String password) {Runnable runnable = new Runnable() {public void run() {try {RedisUtil instance = RedisUtil.getInstance(host, port, password);List<String> resList = instance.getall(key);//recover blackListif(resList != null && resList.size() > 0) {blackList.clear();for (String res : resList) {blackList.add(res);}}} catch (Exception e) {LOG.error("error to get blackList from redis", e);}}};ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();// 第一次执行的时间为0秒,然后每隔120秒执行一次service.scheduleAtFixedRate(runnable, 0, 2*60, TimeUnit.SECONDS);}

更多推荐

java调度方法记录

本文发布于:2024-03-23 01:36:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1738923.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!