任务:每x分钟运行一组操作

时间:2015-12-05 22:16:54

标签: java-ee twitter scheduled-tasks

我必须处理 Twitter API 中的费率限制。

我选择使用任务以免被阻止。

我想知道是否有任何方法每x分钟执行一系列操作(调用不同的方法)

例如,我可以每15分钟发出80个请求。我们假设我必须调用方法a()和b();分别为120次和80次。

我必须完成任务:

a()被召唤:80次 ......等15分钟 a()被召唤:40次 b()被召唤:40次 ......等15分钟 b()被召唤:40次

1 个答案:

答案 0 :(得分:1)

您可以使用Java EE Con​​ccurency Utilities ManagedScheduledExecutorService API完成此任务。

您有两种适用于您的用例的方法:

  1. scheduleAtFixedRate(Runnable r, long initDelay, long period, TimeUnit unit)
  2. scheduleWithFixedDelay(Runnable r, long initDelay, long period, TimeUnit unit)
  3. 这两者之间的唯一区别是scheduleAtFixedRate将每period个TimeUnit运行一次。而scheduleWithFixedDelay将在上一次执行完成后运行period TimeUnit的 。因此,如果您的任务运行得非常快,那么这两种方法基本相同。

    注意:此API是在Java EE 7中引入的。如果您在EE 6或更低版本上运行,请改用Java SE的ScheduledExecuorService

    要在Java EE环境中获取实例:
    注入它:

    @Resource
    ManagedScheduledExecutorService scheduledExec;
    

    或查找:

    ManagedScheduledExecutorService scheduledExec = 
        (ManagedScheduledExecutorService) new InitialContext.lookup(
            "java:comp/DefaultManagedScheduledExecutorService");
    

    使用它:

    // Sample runnables
    // Call a() 80 times
    Runnable a = new Runnable(){
        public void run() {
            for(int i = 0; i < 80; i++)
                a();
        }
    };
    // Call b() 120 times
    Runnable b = new Runnable(){
        public void run() {
            for(int i = 0; i < 120; i++)
                b();
        }
    };
    
    // Submit and run.  Will repeat every 15 minutes until cancelled
    scheduledExec.scheduleWithFixedDelay(a, 0, 15, TimeUnit.MINUTES);
    scheduledExec.scheduleWithFixedDelay(b, 0, 15, TimeUnit.MINUTES);
    
    // scheduleWithFixedDelay also returns a ScheduledFuture,
    // which can be used to monitor and cancel your tasks
    ScheduledFuture<?> future = managedExec.scheduleWithFixedDelay(...);
    future.cancel(true);