从main运行一次类

时间:2015-03-05 14:24:46

标签: java timertask

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

完成的。

课程&方法我想运行一次包含一个计时器任务,确定何时发送电子邮件。其构造如下:

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

1 个答案:

答案 0 :(得分:1)

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

TimerTask的javadoc具有以下'取消':

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

  

public boolean cancel()

     

取消此计时器任务。如果任务已安排一次性   执行,尚未运行,或尚未安排,它会   永远不会跑。如果任务已经安排重复执行,那么   永远不会再跑。 (如果此调用发生时任务正在运行,   任务将运行完成,但永远不会再运行。)

     

请注意,从a的run方法中调用此方法   重复计时器任务绝对保证计时器任务将   不要再跑了。

     

这种方法可以重复调用;第二次和后续的电话   没有效果。

相关问题