简体   繁体   中英

Having trouble getting java program to run scheduled or as infinite loop with sleep timer

So I have written up a rather large program which in the long is supposed to look at a file, if its been updated since the last iteration, turn that file into a webpage (you can ignore the details of what its doing with all this because its functional), FTPs to my website, and then sleeps.

Here is the "best" functional version of my program I have:

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 PrintOutConvosFtp4
{
public static void main(String[] args) throws IOException, InterruptedException
    {
    boolean infiniteLoop = true;
    long currentLoopModified = 0;
    long lastLoopModified = 0;

    while (infiniteLoop)
    {
    currentLoopModified = new File("C:/Documents and Settings/Cuckoo/Desktop/Syss-convos.LOG").lastModified();
    if (currentLoopModified > lastLoopModified)
    {

    //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.")
        || line.contains("just hung up!!!")))
 {
 //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



//define variables for FTP process
String server = "31.170.166.123";
int port = 21;
String user = "username317661";
String pass = "fakepass";

//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 ftpTimestamp = new Timestamp(currentDate.getTime());
    //Create writer file to log iterations of the loop as successful or skipped.
    Writer writer = new BufferedWriter(new FileWriter("C:/Documents and Settings/Cuckoo/Desktop/Convo-Upload.log", true));
    writer.append("Successfully uploaded file as of " + ftpTimestamp.toString() + System.getProperty("line.separator"));
    writer.close(); 
    ftpClient.logout();
} catch (IOException e) {
    //turn the stack trace into a string and output to the log file
    StackTraceElement[] stack = e.getStackTrace();
    String theTrace = "";
    for(StackTraceElement IOstackline : stack)
    {
       theTrace += IOstackline.toString() + System.getProperty("line.separator");
    }
    Writer writer = new BufferedWriter(new FileWriter("C:/Documents and Settings/Cuckoo/Desktop/Convo-Upload.log", true));
    writer.append(theTrace + System.getProperty("line.separator"));
    writer.close(); 
} finally {
    try {
        if (fis != null) {
            fis.close();
        }
        ftpClient.disconnect();
    } catch (IOException e) {
        //turn the stack trace into a string and output to the log file
        StackTraceElement[] stack = e.getStackTrace();
        String theTrace = "";
        for(StackTraceElement IOstackline : stack)
        {
           theTrace += IOstackline.toString() + System.getProperty("line.separator");
        }
        Writer writer = new BufferedWriter(new FileWriter("C:/Documents and Settings/Cuckoo/Desktop/Convo-Upload.log", true));
        writer.append(theTrace + System.getProperty("line.separator"));
        writer.close();
        e.printStackTrace();
        }
    }


lastLoopModified = currentLoopModified; //set the timestamp for the lastmodified on the file being read in

}
    else
    {
        java.util.Date currDate = new java.util.Date();
        Timestamp currTimestamp = new Timestamp(currDate.getTime());
        //Create writer file to log iterations of the loop as successful or skipped.
        Writer writer = new BufferedWriter(new FileWriter("C:/Documents and Settings/Cuckoo/Desktop/Convo-Upload.log", true));
        writer.append("Did not detect any new content in file.  Did not upload as of " + currTimestamp.toString() + System.getProperty("line.separator"));
        writer.close(); 
    }
    Thread.sleep(300000); //5 minutes
}

}
}

This code seems to work in Eclipse or if I import it as a runnable jar file and run from a command prompt, however the log files it creates seem to cease updating after a varying amount of time. A friend advised this is due to how the Thread.sleep functions and that I should try to use a Timer instead. My best attempt at adapting my code to fit a template I found online is as follows:

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 PrintOutConvosFtp7
{
    Timer timer;
    long currentLoopModified = 0;
    long lastLoopModified = 0;
    File file = new File("C:/Documents and Settings/Cuckoo/Desktop/Convo-Upload.log");


    public PrintOutConvosFtp7(int seconds) 
    {
        timer = new Timer();
        timer.schedule(new RemindTask(), seconds*1000);
    }
    class RemindTask extends TimerTask
    {
        @Override
        public void run() 
        {
            try

            {
            Writer writer = new BufferedWriter(new FileWriter("C:/Documents and Settings/Cuckoo/Desktop/Convo-Upload.log", true));  
            currentLoopModified = new File("C:/Documents and Settings/Cuckoo/Desktop/Syss-convos.LOG").lastModified();
            if (currentLoopModified > lastLoopModified)
            {


                //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>();
                FileWriter outputUserLog = new FileWriter("C:/Documents and Settings/Cuckoo/Desktop/Online-Users.log");
                List<String> linesForUserLog = 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);
                            if (line.contains("Current number of users online:"))
                            {
                                linesForUserLog.add(month + "/" + day + line.substring(5));
                            }
                            else
                            {
                                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

        //create the User Log file

        for (ListIterator<String> iter2 = linesForUserLog.listIterator(); iter2.hasNext(); ) 
        {
            String currentline = iter2.next();
            outputUserLog.write(System.getProperty("line.separator") + currentline);
        }
        outputUserLog.close();

        //define variables for FTP process
        String server = "31.175.136.123";
        int port = 21;
        String user = "userfake";
        String pass = "Pa$$w0rD";

        //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 ftpTimestamp = new Timestamp(currentDate.getTime());
            //Create writer file to log iterations of the loop as successful or skipped.
            writer.append("Successfully uploaded file as of " + ftpTimestamp.toString() + System.getProperty("line.separator"));
            ftpClient.logout();
            } catch (IOException e) 
                {
                //turn the stack trace into a string and output to the log file
                StackTraceElement[] stack = e.getStackTrace();
                String theTrace = "";
                for(StackTraceElement IOstackline : stack)
                    {
                        theTrace += IOstackline.toString() + System.getProperty("line.separator");
                    }
                writer.append(theTrace + System.getProperty("line.separator"));
                } 
                finally 
                {
                    try {
                        if (fis != null) 
                            {
                            fis.close();
                            }
                        ftpClient.disconnect();
                        } catch (IOException e) 
                            {
                                //turn the stack trace into a string and output to the log file
                                StackTraceElement[] stack = e.getStackTrace();
                                String theTrace = "";
                                for(StackTraceElement IOstackline : stack)
                                    {
                                        theTrace += IOstackline.toString() + System.getProperty("line.separator");
                                    }
                                writer.append(theTrace + System.getProperty("line.separator"));
                            }
                }
        lastLoopModified = currentLoopModified; //set the timestamp for the lastmodified on the file being read in
            }




    else
    {
        java.util.Date currDate = new java.util.Date();
        Timestamp currTimestamp = new Timestamp(currDate.getTime());
        //Create writer file to log iterations of the loop as successful or skipped.
        writer.append("Did not detect any new content in file.  Did not upload as of " + currTimestamp.toString() + System.getProperty("line.separator"));
    }
            }

    catch (IOException e)
    {
        StackTraceElement[] stack = e.getStackTrace();
        String theTrace = "";
        for(StackTraceElement IOstackline : stack)
            {
                theTrace += IOstackline.toString() + System.getProperty("line.separator");
            }
        PrintWriter pw = null;
        try {
            pw = new PrintWriter(file);
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block -- this file should never be missing
            e1.printStackTrace();
        }
        e.printStackTrace(pw);
        pw.close();
    }


    timer.cancel(); // Terminate the timer thread
}
}
public static void main (String args[]) 
{
    new PrintOutConvosFtp7(600); //10 minute timer = 600 seconds
}
}       

This compiles and runs, but none of the logs are being updated at all which leads me to believe it's not doing anything at all. I had to add some extra try catch BS in there because I suck at scope and exceptions and was having difficulty getting it to run at all. Maybe I messed up a squiggly bracket somewhere but please if anyone can help or suggest an alternative way to achieve this so that the program will just continually run regardless of silly FTP failure errors, etc

Basically, don't use an inifinite loop, and don't code inside your program the logic to run it every X unit of time. Instead, write it to run once (much easier), and use something like cron on linux or Windows Task Scheduler on windows to have it run on a regular base.

A third option would be to have a continuous build software like Jenkins launch it at regular intervals.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM