繁体   English   中英

如何间隔执行某些任务(任务计划)

[英]how to execute certain tasks in intervals(task schedular)

我有某种类型的任务,例如在循环中使用相同的方法但使用不同的参数,我需要在一定时间间隔内一次又一次地执行这些任务,并且所有这些活动都需要在特定的时间表中一次又一次地执行,例如假设我有一个方法叫做

public void GetData(String tablename){
}

所以第一次我将提供table1然后提供table2然后提供table3 .....类似于for循环,但之间需要一定的间隔,

最重要的是每10分钟执行一次,

我已经实现为示例代码

final ScheduledExecutorService scheduler =
                Executors.newScheduledThreadPool(1);
final Runnable runner = new Runnable() {
                  public void run() { 
                      getData(String table);
                      }
                };
                final ScheduledFuture<?> taskHandle =
                  scheduler.scheduleAtFixedRate(runner, 1, 10, SECONDS);

它对于一个表的工作正常,需要帮助,并且是实现多个表的最佳方法。

tryjava.util.Timer计划要执行的任务

        public class ReminderBeep {
              Toolkit toolkit;

              Timer timer;

              public ReminderBeep(int seconds) {
                toolkit = Toolkit.getDefaultToolkit();
                timer = new Timer();
                timer.schedule(new RemindTask(), seconds * 1000);
              }

              class RemindTask extends TimerTask {
                public void run() {
                  System.out.println("Time's up!");
          toolkit.beep();
          //timer.cancel(); //Not necessary because we call System.exit
          System.exit(0); //Stops the AWT thread (and everything else)
            }
          }

          public static void main(String args[]) {
            System.out.println("About to schedule task.");
        new ReminderBeep(5);
        System.out.println("Task scheduled.");
          }
        }

您可以只在循环中使用Thread.sleep()(如果它不在主线程上)。 这样的事情(代码未经测试,因此可能包含错误):

ExecutorService executorService = Executors.newFixedThreadPool(4);
for (int i = 0; i < 10; i++) {
     executorService.execute(new Runnable() {
     public void run() {
         getData(String table);
     }
     Thread.sleep(10000);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM