运行 class 一次来自 main

Run class once from main

我不确定这是否可行,但我想在我的应用程序的 Main class 中实例化一个 class,这样它只会 运行 一次。我有一个特别的问题,因为我的应用程序多次回调到 main 作为应用程序重启的一种方式,这是按 ConToDatabase.main(args);

完成的

我想 运行 的 class & 方法曾经包含一个计时器任务,用于确定何时发送电子邮件。构造如下:

class EmailSending extends TimerTask
    {
        public static FileInputStream propFile;
        static Connection conn = null;
        static Statement query = null;
        static String path;
        static FunctionLogging logger = new FunctionLogging(path, true);
        static Statement stmnt;
        public void run()
        {
            try
            {
                logger.writeToFile("Entered Class|EmailSending");
                Date date = new Date();     
                SimpleDateFormat mailDate = new SimpleDateFormat();
                mailDate = new SimpleDateFormat("dd-MM-yy HH:mm:ss");
                String mail = mailDate.format(date);
                propFile = new FileInputStream("config.ini");
                Properties config = new Properties(System.getProperties()); 
                config.load(propFile);
                String host = config.getProperty("host");
                String port = config.getProperty("port");
                path = config.getProperty("path");
                String DB_URL = config.getProperty("DB_URL");
                String USER = config.getProperty("USER");
                String PASS = config.getProperty("PASS");
                path = config.getProperty("path");
                Class.forName("com.mysql.jdbc.Driver");
                conn = DriverManager.getConnection(DB_URL, USER, PASS);

                String sender = config.getProperty("sender");
                Properties toRecipients = System.getProperties();
                Session current = Session.getDefaultInstance(toRecipients);
                toRecipients.setProperty("mail.smtp.host", host);
                toRecipients.setProperty("mail.smtp.port", port);
                MimeMessage message = new MimeMessage(current);
                message.setFrom(new InternetAddress(sender));
                String[] recipients = config.getProperty("EmailList").split(";");
                for(int i=0;i<recipients.length;i++)
                {
                    message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients[i].trim()));
                    logger.writeToFile("EmailSending Class|Method: run|Recipient: ["+recipients[i].trim()+"] found");
                    message.setSubject("Results of Audit Trail "+mail);
                    message.setText(messageBody().toString());
                    logger.writeToFile("EmailSending Class|emailSend Method|Sending emails");
                    Transport.send(message);
                }
            }
            catch (MessagingException me)
            {
                System.out.println(me.getMessage());
            }
            catch (FileNotFoundException fnf)
            {
                System.out.println(fnf.getMessage());
            }
            catch (IOException ioe)
            {
                System.out.println(ioe.getMessage());
            }
            catch (SQLException sqle)
            {
                System.out.println(sqle.getMessage());
            }
            catch (ClassNotFoundException cnf)
            {
                System.out.println(cnf.getMessage());
            }
        }
        public static void emailSend(int control) throws IOException
        {
            logger.writeToFile("EmailSend Class|Method: emailSend|Timer Started");
            Timer timer = new Timer();
            timer.schedule(new EmailSending(), 0, control*60000);
            logger.writeToFile("EmailSend Class|Method: emailSend|Timer Completed. Sleeping for ["+control+"] minute(s)");
        }
        private static StringBuilder messageBody() throws SQLException
        {
            stmnt = conn.createStatement();
            String SQL = "Select Action from Java_Test_AuditTrail";
            ResultSet rs1 = stmnt.executeQuery(SQL);
            rs1.last();
            int rowNumb = rs1.getRow();
            int list = 0;
            int delete = 0;
            int update = 0;
            int load = 0;
            int upload = 0;
            int display = 0;
            int add = 0;
            rs1.beforeFirst();
            rs1.next();
            int seeker=1;
            while(rs1.next()&&seeker<=rowNumb)
            {
                String actExecuted = rs1.getString("Action");
                if(actExecuted.equals("LIST"))
                {
                    list++;
                }
                if(actExecuted.equals("DELETE"))
                {
                    delete++;
                }
                if(actExecuted.equals("UPDATE"))
                {
                    update++;
                }
                if(actExecuted.equals("RE-LOAD"))
                {
                    load++;
                }
                if(actExecuted.equals("UPLOAD"))
                {
                    upload++;
                }
                if(actExecuted.equals("DISPLAY AUDIT"))
                {
                    display++;
                }
                if(actExecuted.equals("USER_CREATED"))
                {
                    add++;
                }               
            }
            StringBuilder builder = new StringBuilder();
            builder.append("Since Creation of the database, there have been: ["+list+"] List requests executed"+"\n");
            builder.append("\n");
            builder.append("Since Creation of the database, there have been: ["+delete+"] Delete requests executed"+"\n");
            builder.append("\n");
            builder.append("Since Creation of the database, there have been: ["+update+"] Update requests executed"+"\n");
            builder.append("\n");
            builder.append("Since Creation of the database, there have been: ["+load+"] Re-load requests executed"+"\n");
            builder.append("\n");
            builder.append("Since Creation of the database, there have been: ["+upload+"] Upload requests executed"+"\n");
            builder.append("\n");
            builder.append("Since Creation of the database, there have been: ["+display+"] Audit-Display requests executed"+"\n");
            builder.append("\n");
            builder.append("Since Creation of the database, there have been: ["+add+"] User-Creation requests executed"+"\n");
            return builder;
        }   
    }

也许在工作结束时调用 'cancel' 方法?

TimerTask 的 javadocs 有以下 'cancel':

http://docs.oracle.com/javase/7/docs/api/java/util/TimerTask.html

public boolean cancel()

Cancels this timer task. If the task has been scheduled for one-time execution and has not yet run, or has not yet been scheduled, it will never run. If the task has been scheduled for repeated execution, it will never run again. (If the task is running when this call occurs, the task will run to completion, but will never run again.)

Note that calling this method from within the run method of a repeating timer task absolutely guarantees that the timer task will not run again.

This method may be called repeatedly; the second and subsequent calls have no effect.