java设置指定时间调用方法,如何在java中的特定时间调用方法?

Is it possible to call a method in java at specific time? For examplef I have a piece of code like this:

class Test{

....

// parameters

....

public static void main(String args[]) {

// here i want to call foo at : 2012-07-06 13:05:45 for instance

foo();

}

}

How this can be done in java?

解决方案

Using a java.util.Timer class you can create a timer and schedule it to run at specific time.

Below is the example:

//The task which you want to execute

private static class MyTimeTask extends TimerTask

{

public void run()

{

//write your code here

}

}

public static void main(String[] args) {

//the Date and time at which you want to execute

DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

Date date = dateFormatter .parse("2012-07-06 13:05:45");

//Now create the time and schedule it

Timer timer = new Timer();

//Use this if you want to execute it once

timer.schedule(new MyTimeTask(), date);

//Use this if you want to execute it repeatedly

//int period = 10000;//10secs

//timer.schedule(new MyTimeTask(), date, period );

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值