每10分钟调用一次函数

我不是专家,只是初学者。 所以我恳请你为我写一些代码。

如果我有两个类, CLASS ACLASS B ,并且在CLASS B有一个名为funb()的函数。 我想每十分钟从CLASS A调用一次这个函数。

你已经给了我一些想法,但我不太明白。

你能发布一些示例代码吗?

看看ScheduledExecutorService :

这是一个带有方法的类,该方法将ScheduledExecutorService设置为每隔十秒钟发出一小时的哔声:

  import static java.util.concurrent.TimeUnit.*; class BeeperControl { private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); public void beepForAnHour() { final Runnable beeper = new Runnable() { public void run() { System.out.println("beep"); } }; final ScheduledFuture beeperHandle = scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS); scheduler.schedule(new Runnable() { public void run() { beeperHandle.cancel(true); } }, 60 * 60, SECONDS); } } 
 import java.util.Date; import java.util.Timer; import java.util.TimerTask; public class ClassExecutingTask { long delay = 10 * 1000; // delay in milliseconds LoopTask task = new LoopTask(); Timer timer = new Timer("TaskName"); public void start() { timer.cancel(); timer = new Timer("TaskName"); Date executionDate = new Date(); // no params = now timer.scheduleAtFixedRate(task, executionDate, delay); } private class LoopTask extends TimerTask { public void run() { System.out.println("This message will print every 10 seconds."); } } public static void main(String[] args) { ClassExecutingTask executingTask = new ClassExecutingTask(); executingTask.start(); } } 

尝试这个。 它会在每个分钟内重复run()函数。 要更改设置的分钟数,请更改MINUTES变量

 int MINUTES = 10; // The delay in minutes Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { // Function runs every MINUTES minutes. // Run the code you want here CLASSB.funcb(); // If the function you wanted was static } }, 0, 1000 * 60 * MINUTES); // 1000 milliseconds in a second * 60 per minute * the MINUTES variable. 

别忘了做import!

 import java.util.Timer; import java.util.TimerTask; 

有关更多信息,请转到此处:

http://docs.oracle.com/javase/7/docs/api/java/util/Timer.html http://docs.oracle.com/javase/7/docs/api/java/util/TimerTask.html

 public class datetime { public String CurrentDate() { java.util.Date dt = new java.util.Date(); java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String currentTime = sdf.format(dt); return currentTime; } public static void main(String[] args) { class SayHello extends TimerTask { datetime thisObj = new datetime(); public void run() { String todaysdate = thisObj.CurrentDate(); System.out.println(todaysdate); } } Timer timer = new Timer(); timer.schedule(new SayHello(), 0, 5000); } }