开发者

Java: addScheduledJobAfterDelay() - can I force a scheduled job to start?

开发者 https://www.devze.com 2022-12-29 01:02 出处:网络
I\'m developing a poker game. On the betting stage I create a scheduled job using Red5 iSchedulingService that will run every 8 seconds to forward to the next player to place a bet. Now if the user pl

I'm developing a poker game. On the betting stage I create a scheduled job using Red5 iSchedulingService that will run every 8 seconds to forward to the next player to place a bet. Now if the user placed a bet before the 8 seconds are over, I want to manually force the next scheduled job to start.

Is there a way to force the scheduled job to start immediately 开发者_StackOverflow社区when required?


You can do this with Executors. There are cleaner implementations, but this is a stab and something basic that does what you want using Future and Callable.

// wherever you set up the betting stage
ScheduledExecutorService bettingExecutor = 
    Executors.newSingleThreadScheduledExecutor();

ScheduledFuture<?> future = bettingExecutor.schedule(new BettingStage(), 8,
    TimeUnit.SECONDS);

//...

// in the same class (or elsewhere as a default/protected/public class)
private class BettingStage implements Callable<ScheduledFuture<?>> () {
    public ScheduledFuture<?> call() thows ExecutionException {
        ScheduledFuture<?> future = bettingExecutor.schedule(new BettingStage(), 8, 
            TimeUnit.SECONDS);
        // betting code here
        boolean canceled = future.cancel(false); // cancels the task if not running yet
        if(canceled) {
             // run immediately
             future = bettingExecutor.schedule(new BettingStage(), 
                0, TimeUnit.SECONDS)
        }
        return future;
    }
}


an answer to my specific question that I started with in this thread:

i cannot force to start a scheduled job, but what I can do is remove the scheduled job and start a new job with a delay of 0 seconds.

addScheduledJobAfterDelay() return a string that represents the job id. i can use it to remove the scheduled job. The problem is that there is no way to know if I'm interrupting the scheduled job or not. Executors do provide that information. that is why Executors are better choice in this specific case then using the red5 scheduling service.

how to remove a scheduled job (red5):

ISchedulingService scheduler = (ISchedulingService) getScope().getContext().getBean(ISchedulingService.BEAN_NAME);
     scheduler.removeScheduledJob("ScheduleJobString");

the string ScheduleJobString should be replaced with the string that you have received from creating the job:

String scheduleJobString = scheduler.addScheduledOnceJob(DelayInSeconds*1000,new MyJob());
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号