如何在java中的指定时间自动执行函数 [英] How to execute function automatically at specified time in java

查看:2391
本文介绍了如何在java中的指定时间自动执行函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要求,我需要在用户设置的指定时间执行一个函数。该函数包含从数据库生成pdf文件的代码,并将其保存到机器的本地驱动器中。
这里的时间需要由用户设置,并且可能会根据他的要求进行更改。

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 ..

以下是代码段..

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..

推荐答案

好的,所以我看了一下Timer类,发现你的方法几乎是正确的。您需要稍微编辑一下代码以获得所需的功能。

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);

这将启动一个在指定时间启动ReportGenerator的计时器。你必须弄清楚如何从用户那里得到输入(应该相当简单!)

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!)

这篇关于如何在java中的指定时间自动执行函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆