使用Java 编写一个简单的定时器
package test; import java.util.Calendar; import java.util.TimerTask; /** * 需要定时间操作的方法 */ public class TimerTest extends TimerTask { @Override public void run() { System.out.println("你好..."+Calendar.getInstance()); } }
package test; import java.util.Date; import java.util.Timer; /**定时器测试*/ public class TimerTestResult { public void execute() { Timer timer = new Timer(); TimerTest task = new TimerTest(); Date date = new Date(); long timestamp = 5000; timer.schedule(task, date, timestamp); } public static void main(String[] args) { TimerTestResult result= new TimerTestResult(); result.execute(); } }
结果:
当然也可以和spring结合的使用,在application-*.xml中的任意一个配置文件中定义
<bean name="taskJob" class="job.MyJob" init-method="job"/>
当然,还可以使用spring定时器自带的插件Quartz.