ScheduledExecutorService仅运行一次 [英] ScheduledExecutorService only runs once

查看:2411
本文介绍了ScheduledExecutorService仅运行一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在启动Web服务之后运行一个进程,然后每30分钟左右运行一次(我现在以较小的延迟对其进行测试,以查看其是否正常运行),但是我的进程从未运行过不止一次.我在做什么错了?

I want a process to run after I start my webservice, and then every 30 minutes or so afterwards, (I'm testing it with a smaller delay for now, just to see if it works), but my process never runs more than once. What am I doing wrong?

这是我的代码:

@WebListener
public class SchedulerService implements ServletContextListener{

    @Autowired
    UpdateSubscriberService updateSubscriberService;

    ScheduledExecutorService scheduledExecService;

    public SchedulerService(){
        scheduledExecService = Executors.newSingleThreadScheduledExecutor();
    }

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        scheduledExecService.shutdown();
    }

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        scheduledExecService.scheduleWithFixedDelay(new Runnable(){
            @Override
            public void run() {
                Date date = new Date(System.currentTimeMillis());
                System.out.println("Running scheduled update check " + date.toString());
                updateSubscriberService.checkForUpdates();
            }
        }, 60, 30, TimeUnit.SECONDS);
    }
}

推荐答案

请参见与此类似的答案问题.

See this longer Answer of mine on a similar Question.

只是一个猜测:正在引发异常. ScheduledExecutorService遇到异常时会默默停止.

Just a guess: An exception is being thrown. A ScheduledExecutorService halts silently if it encounters an Exception.

run方法的代码应始终被try-catch包围,以处理和吸收所有引发的异常.

The run method’s code should always be surrounded by a try-catch to handle and absorb any thrown Exception.

 @Override
 public void run() {
    try {  // Let no Exception reach the ScheduledExecutorService.
        Date date = new Date(System.currentTimeMillis());
        System.out.println("Running scheduled update check " + date.toString());
        updateSubscriberService.checkForUpdates();
    } catch ( Exception e ) {
        System.out.println( "ERROR - unexpected exception" );
    }
}

存根run方法

采取婴儿步骤.从run方法开始,该方法除了System.out.println外什么都不做.

Stub out run method

Take baby steps. Begin with a run method that does nothing but a System.out.println.

这篇关于ScheduledExecutorService仅运行一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆