每天Java调度

时间:2013-09-03 09:47:49

标签: java timer scheduled-tasks scheduling timertask

所以我有工具,首先应用程序检查数据库,然后发送电子邮件。它完成了。对我来说什么问题是调度。我已经阅读了一些计时器任务。我需要在00:00 am每天运行的工具。无论好坏,这是我的代码

package SQLTest;

import java.sql.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import SQLTest.EmailSender;


 public class TestSQL
 {

  public static void sQl(String datesec)
  {
  try
  {
  // create mysql database connection
  String myDriver = "org.gjt.mm.mysql.Driver";
  String myUrl = "jdbc:mysql://localhost;
  Class.forName(myDriver);
  String userName = dbuser;
  String pass = dbpass;
  String checkQa = "check it QA";
  String juDul = "blabla";
  String opcel1 = "opcel1 ";
  String opcel2 = "opcel2 ";
  String opcel3 = "opcel3 ";
  String opcel4 = "opcel4 ";
  String opcel5 = "opcel5 ";
  String opcel6 = "opcel6 ";
  Calendar calendar = Calendar.getInstance();
  calendar.add(Calendar.DATE, -1);
  Date time = (Date) calendar.getTime();
  DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
  String currentDate = dateFormat.format(time);
  Connection conn = DriverManager.getConnection(myUrl, userName , pass );


 String query = "the query"



  Statement st = conn.createStatement();
  ResultSet rs = st.executeQuery(query);

  //java resultset
  while (rs.next())
  {

   int tanggal = rs.getInt("tanggal");


    // print the results
    System.out.format("%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s\n");  

    if(column1 == 0) EmailSender.emailNotification(juDul+opcel1+currentDate, 
    "email Body " + "\n" + checkQa);
    }

  st.close();
}
catch (Exception e)
{
  System.err.println("Got an exception! ");
  System.err.println(e.getMessage());
}
}


}

我是否必须制作新课程来处理日程安排? 是否有一些很好的例子可以通过我的类(TestSQL)进行调度?

提前致谢

编辑:这是我的调度程序类。我设法将它传递给这个班级。

package SQLTest;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Timer;
import java.util.TimerTask;



public final class Scheduler extends TimerTask{

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TimerTask scheduletimer  = new Scheduler();

   //perform the task once a day at 00 a.m., starting tomorrow morning
   //(other styles are possible as well)
   Timer timer = new Timer();

   Timer t = new Timer();
   t.scheduleAtFixedRate(
       new TimerTask()
       {
           public void run()
           {

              System.out.print("========[ 3600 Second Passed ---> 1 Hour  ]=======\n");
           }
       },
       0,      // run first occurrence immediately
       3600000);

   System.out.println("scheduling ==> " + getTomorrowMorning00am());
   try{
   timer.scheduleAtFixedRate(scheduletimer, getTomorrowMorning00am(), fONCE_PER_DAY);
   }catch(Exception e){
    System.out.print("ERROR : " +e);
    }
 }

 /**
 * Implements TimerTask's abstract run method.
 */
 public void run(){
   //here is my class implementation
     System.out.print("===================================================\n");
     System.out.print("schedule Started");
   DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
   Calendar cal = Calendar.getInstance();
   Date date = new Date();
   String datesec = dateFormat.format(date);
  try {
   cal.setTime( dateFormat.parse(datesec));
   } catch (ParseException e) {
  // TODO Auto-generated catch block
  System.out.print("ERROR : " + e);
  }
  cal.add( Calendar.DATE, 0 );    
   datesec = dateFormat.format(cal.getTime());
   **TestSQL.sQl(datesec);**
   System.out.print("===================================================\n");
   System.out.print("scheduling ==> " + getTomorrowMorning00am());
   }

  // PRIVATE ////

  //expressed in milliseconds
  private final static long fONCE_PER_DAY = 1000*60*60*24 ;
  private final static int fONE_DAY = 1;
  private final static int fZERO_AM = 0;
  private final static int fZERO_MINUTES = 0;

  private static Date getTomorrowMorning00am(){
  Calendar tomorrow = new GregorianCalendar();
  tomorrow.add(Calendar.DATE, fONE_DAY);
  Calendar result = new GregorianCalendar(
  tomorrow.get(Calendar.YEAR),
  tomorrow.get(Calendar.MONTH),
  tomorrow.get(Calendar.DATE),
  fZERO_AM,
  fZERO_MINUTES
  );
  return result.getTime();
  }

  }

注意:如果有人对我的代码有其他想法,请随意。它是错的,它是不完整的,还是别的东西。保持分享:D

2 个答案:

答案 0 :(得分:3)

为您的应用程序创建一个Cron作业(计划任务)

Cron由crontab(cron table)文件驱动,该文件是一个配置文件,它指定在给定的时间表上定期运行的shell命令。

参考链接:

  

http://en.wikipedia.org/wiki/Cron

     

http://www.thesitewizard.com/general/set-cron-job.shtml

     

https://www.google.co.in/#q=cron+job+scheduling+steps

对于配置的文件,提供一个.sh文件,其中包含以下用于运行应用程序的示例命令。

cd /home
java -cp ".:./jars/ojdbc14.jar:./jars/commons-logging.jar:./jars/j2ssh-ant-0.2.9.jar:"  -Xms512m -Xmx512m SQLTest.TestSQL 

答案 1 :(得分:2)

您不应该将调度功能与任务实现混淆。您需要的是一个API,它允许您安排在给定时间执行的作业。你可以:

  • 自行实施此类API 。这可以非常简单和直接:为Job建模接口并实现Scheduler,允许在给定时间内安排作业,并轮询现在到期的任务(预定时间< =当前时间)并执行它们。这需要您的调度程序沿您的应用程序运行(单独的线程)。根据环境(客户端,Web容器,应用程序服务器),您需要挂钩生命周期以启动和终止调度程序。
  • 使用现有API ,例如Quartz Scheduler
  • 或者,正如 Thilo 在您的问题的评论中所说:使用Cron(Linux / Unix)或Windows Scheduler使作业成为独立程序并安排。< / LI>