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 blackList
                    if(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);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值