java在指定时间执行,如何在java中的指定时间自动执行函数

I have got a requirement in which i need to execute a function at specified time set by the user.The function contains the code to generate a pdf file from database and save it into local drive of the machine..

Here the time needs to be set by the user and it may be changed depending on his requirement.

I have never used timer class..

I have a code snippet which i got from google but i am not getting how to set the user specific time details for function execution in this code ..

Here is the code snippet..

class ReportGenerator extends TimerTask {

public void run() {

System.out.println("Generating report");

//TODO generate report

}

}

class MainApplication {

public static void main(String[] args) {

Timer timer = new Timer();

Calendar date = Calendar.getInstance();

date.set(

Calendar.DAY_OF_WEEK,

Calendar.SATURDAY);

date.set(Calendar.HOUR, 0);

date.set(Calendar.MINUTE, 0);

date.set(Calendar.SECOND, 0);

date.set(Calendar.MILLISECOND, 0);

// Schedule to run every Sunday in midnight

timer.schedule(

new ReportGenerator(),

date.getTime(),

1000 * 60 * 60 * 24 * 7);

}

}

I am also not getting the meaning of this code snippet..what does this means??

timer.schedule(

new ReportGenerator(),

date.getTime(),

1000 * 60 * 60 * 24 * 7);

}

In the above code snippet the given function will execute on every saturday .

Please help me .Any idea is heartely welcomed ...

Thanks in advance..

解决方案

Okay, so I looked a bit into the Timer class and found your approach to be almost correct. You'll need to edit your code a little bit to get the wanted functionality.

Calendar calendar = Calendar.getInstance();

date.set(Calendar.DAY_OF_WEEK, getUserInputDay()); //

calendar.set(Calendar.HOUR_OF_DAY, getUserInputHour());

calendar.set(Calendar.MINUTE, getUserInputMinute());

calendar.set(Calendar.SECOND, getUserInputSeconds());

Date time = calendar.getTime();

timer = new Timer();

timer.schedule(new ReportGenerator(), time);

This will start a timer that launches the "ReportGenerator" at the stated time. You'll have to figure out yourself how to get the input from the user (should be fairly simple!)

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值