如何调整我的java程序以定期连续运行和执行?

时间:2014-07-19 09:16:26

标签: java sleep intervals schedule

我编写了以下java部分,它获取了一个纯文本文件,将其转换为HTML文件,然后将该文件FTP到Web服务器。由于明文源文件不断更新,我希望这可以在半定期的基础上继续运行。我研究了在Windows XP中使用任务计划程序(是的,我在恐龙机器上),但最常见的选择是每天一次。是否有一种有效/简单的方法来使用睡眠命令并且每15分钟/小时执行一次?

我包含了我的上下文代码:

import java.io.*;
import java.util.*;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import java.sql.Timestamp;

public class PrintOutConvosFtp2
{
public static void main(String[] args) throws IOException
    {

    //Read in the conversation log
BufferedReader reader = new BufferedReader(new FileReader("C:/Documents and Settings/Cuckoo/Desktop/Syss-convos.LOG"));
FileWriter output = new FileWriter("C:/Documents and Settings/Cuckoo/Desktop/Conversations.html");
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = reader.readLine()) != null)
    //remove some unnecessary clutter from the log
 {
 if (!(line.contains("just hung up!!!") || line.contains("just left the Realm.")
        || line.contains("Hurry, I've many esoteric secrets to divulge, and welcome to BaDbOy's realm.")
        || line.contains("For custom MegaMud paths and additional information, check out the website:")
        || line.contains("Syss gossips: Discuss new ideas/issues & see the most up to date information on Facebook!")
        || line.contains("Syss gossips: http://www.facebook.com/groups/EsotericEdits/")
        || line.contains("Syss gossips: MME Dats, Megamud path files and quest walkthroughs are available at my site")
        || line.contains("Syss gossips: www.esoteric-edits.fhero.net")
        || line.contains("telepaths: @")
        || line.contains("I'm a bot.  Try telepathing me with @commands.")
        || line.contains("Syss gossips: Remember, you can telepath me @commands for useful things like adding lives.")
        || line.contains("Syss gossips: Bring a friend, help keep mud alive!")
        || line.contains("You say \"http://esoteric-edits.fhero.net/\"")
        || line.contains("For a list of available commands, you can telepath me with @commands.")))
 {
 //make the dates american style
     String day = line.substring(0,2);
     String month = line.substring(3,5);
lines.add(month + "/" + day + line.substring(5));
}


 }
//initialize the output file with HTML header
output.write("<html>");
output.write(System.getProperty("line.separator") + "\t<head>");
output.write(System.getProperty("line.separator") + "\t\t<link type=\"text/css\" rel=\"stylesheet\" href=\"stylesheet.css\"/>");
output.write(System.getProperty("line.separator") + "\t\t<title>Esoteric Edits BBS - Conversation Log</title>");
output.write(System.getProperty("line.separator") + "\t</head>");
output.write(System.getProperty("line.separator") + "\t<body>"+ System.getProperty("line.separator") + System.getProperty("line.separator"));
output.write(System.getProperty("line.separator") + "<div id='cssmenu'>");
output.write(System.getProperty("line.separator") + "\t\t<center><img src=\"logo_10_2.png\">");
output.write(System.getProperty("line.separator") + "<ul>");
output.write(System.getProperty("line.separator") + "\t<li> <a href='index.html'><span>Home</span></a></li>");
output.write(System.getProperty("line.separator") + "\t<li> <a href='downloads.html'><span>Downloads</span></a></li>");
output.write(System.getProperty("line.separator") + "\t<li> <a href='Quests.html'><span>Quest Walkthroughs</span></a></li>");
output.write(System.getProperty("line.separator") + "\t<li> <a href='https://www.facebook.com/groups/EsotericEdits/'><span>Facebook</span></a></li>");
output.write(System.getProperty("line.separator") + "\t<li> <a href='captures.html'><span>Captures</span></a></li>");
output.write(System.getProperty("line.separator") + "\t<li class='last'> <a href='FAQs.html'><span>FAQs</span></a></li>");
output.write(System.getProperty("line.separator") + "</ul></center>");
output.write(System.getProperty("line.separator") + "</div><div id='mainpage'>");
output.write(System.getProperty("line.separator") + "<center><img src=\"divider.png\"></center>");

//write out a new file with HTML coloration
for (ListIterator<String> iter = lines.listIterator(); iter.hasNext(); ) 
{
    String currentline = iter.next();
    output.write("<b>"); //make everything bold
    if (currentline.contains("gangpaths: "))
{
output.write(System.getProperty("line.separator") + "<font color=\"#808000\">" + currentline + "<br></font>");
}
    else if (currentline.contains("gossips: ") || currentline.contains("auctions: "))
{
output.write(System.getProperty("line.separator") + "<font color=\"#FF00FF\">" + currentline + "<br></font>");
}
else if (currentline.contains("Broadcast from "))
{
output.write(System.getProperty("line.separator") + "<font color=\"yellow\">" + currentline + "<br></font>");
}
else if (currentline.contains("says \"") || currentline.contains("greets you.") || currentline.contains("bows deeply.")
             || currentline.contains("breaks into a wide grin.") || currentline.contains("You say \"") 
             || currentline.contains("nods affirmatively.") || currentline.contains("grin slyly"))
{
output.write(System.getProperty("line.separator") + "<font color=\"green\">" + currentline + "<br></font>");
}
else
{
output.write(System.getProperty("line.separator") + currentline + "<br>");
}
}
//finalize the HTML footer
output.write(System.getProperty("line.separator") + "</b>");
output.write(System.getProperty("line.separator") + "</div>");
output.write(System.getProperty("line.separator") + "</body>");
output.write(System.getProperty("line.separator") + "\t</html>");
output.close(); //file is finalized locally

//Log file location for FTPs
Writer writer = new BufferedWriter(new FileWriter("C:/Documents and Settings/Cuckoo/Desktop/Convo-Upload.log", true));

//define variables for FTP process
String server = "servername";
int port = 21;
String user = "fake";
String pass = "password";

//begin FTP process to web server
FTPClient ftpClient = new FTPClient();
FileInputStream fis = null;
try {

    File localFile = new File("C:/Documents and Settings/Cuckoo/Desktop/Conversations.html");
    ftpClient.connect(server, port);
    ftpClient.login(user, pass);
    ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
    fis = new FileInputStream(localFile);
    String remoteFile = "/public_html/Conversations.html";
    ftpClient.storeFile(remoteFile, fis);
    java.util.Date currentDate = new java.util.Date();
    Timestamp currentTimestamp = new Timestamp(currentDate.getTime());
    writer.append("Successfully uploaded file as of " + currentTimestamp.toString() + System.getProperty("line.separator"));
    ftpClient.logout();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        if (fis != null) {
            fis.close();
        }
        ftpClient.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
        }
    }

writer.close(); //close the FTP logger
}
}

2 个答案:

答案 0 :(得分:2)

您可以在执行逻辑之间让程序休眠15分钟。这样程序就会不断运行(不需要调度程序重新启动它),但它会在没有执行任何操作的情况下进行休眠。当然,如果程序退出/崩溃,您需要以某种方式注意并重新启动它。

基本上将它全部包含在while循环中,并在循环结束时添加Thread.sleep(...);

答案 1 :(得分:1)

可以将Windows XP任务计划程序设置为更频繁地运行。您需要转到Advanced标签。请参阅此回答How to schedule task to run every 10 minutes, from 8:00 to 15:00 on multiple days of week (with schtask.exe)?

或者,您可以使用Watch Service API。有关详细信息,请参阅http://docs.oracle.com/javase/tutorial/essential/io/notification.html。请注意,这需要Java 1.7或更高版本。

&#34; java.nio.file包提供了一个名为Watch Service API的文件更改通知API。此API使您可以使用监视服务注册目录(或多个目录)。注册时,您告诉服务您感兴趣的事件类型:文件创建,文件删除或文件修改。当服务检测到感兴趣的事件时,它将被转发到注册的进程。已注册的进程有一个线程(或一个线程池),专门用于监视它已注册的任何事件。当一个事件进入时,它会根据需要进行处理。&#34;