關(guān)于定時任務(wù),似乎跟時間操作的聯(lián)系并不是很大,但是前面既然提到了定時任務(wù),索性在這里一起解決了。
設(shè)置定時任務(wù)很簡單,用Timer類就搞定了。
一、延時執(zhí)行
首先,我們定義一個類,給它取個名字叫TimeTask,我們的定時任務(wù),就在這個類的main函數(shù)里執(zhí)行。代碼如下:
package test;
import java.util.Timer;
public class TimeTask {
public static void main(String[] args){
Timer timer = new Timer();
timer.schedule(new Task(), 60 * 1000);
}
}
解釋一下上面的代碼。
上面的代碼實現(xiàn)了這樣一個功能,當(dāng)TimeTask程序啟動以后,過一分鐘后執(zhí)行某項任務(wù)。很簡單吧:先new一個Timer對象,然后調(diào)用它的schedule方法,這個方法有四個重載的方法,這里我們用其中一個,
public void schedule(TimerTask task,long delay)
首先,第一個參數(shù)
第一個參數(shù)就是我們要執(zhí)行的任務(wù)。
這是一個TimerTask對象,確切點說是一個實現(xiàn)TimerTask的類的對象,因為TimerTask是個抽象類。上面的代碼里面,Task就是我們自己定義的實現(xiàn)了TimerTask的類,因為是在同一個包里面,所以沒有顯性的import進(jìn)來。Task類的代碼如下
package test;
import java.util.TimerTask;
public class Task extends TimerTask {
public void run(){
System.out.println("定時任務(wù)執(zhí)行");
}
}
我們的Task必須實現(xiàn)TimerTask的方法run,要執(zhí)行的任務(wù)就在這個run方法里面,這里,我們只讓它往控制臺打一行字。
第二個參數(shù)
第二個參數(shù)是一個long型的值。這是延遲的時間,就是從程序開始以后,再過多少時間來執(zhí)行定時任務(wù)。這個long型的值是毫秒數(shù),所以前面我們的程序里面,過一分鐘后執(zhí)行用的參數(shù)值就是 60 * 1000。
二、循環(huán)執(zhí)行
設(shè)置定時任務(wù)的時候,往往我們需要重復(fù)的執(zhí)行這樣任務(wù),每隔一段時間執(zhí)行一次,而上面的方法是只執(zhí)行一次的,這樣就用到了schedule方法的是另一個重載函數(shù)
public void schedule(TimerTask task,long delay,long period)
前兩個參數(shù)就不用說什么了,最后一個參數(shù)就是間隔的時間,又是個long型的毫秒數(shù)(看來java里涉及到時間的,跟這個long是脫不了干系了),比如我們希望上面的任務(wù)從第一次執(zhí)行后,每個一分鐘執(zhí)行一次,第三個參數(shù)值賦60 * 1000就ok了。
三、指定執(zhí)行時間
既然號稱是定時任務(wù),我們肯定希望由我們來指定任務(wù)指定的時間,顯然上面的方法就不中用了,因為我們不知道程序什么時間開始運行,就沒辦法確定需要延時多少。沒關(guān)系,schedule四個重載的方法還沒用完呢。用下面這個就OK了:
public void schedule(TimerTask task,Date time)
比如,我們希望定時任務(wù)2006年7月2日0時0分執(zhí)行,只要給第二個參數(shù)傳一個時間設(shè)置為2006年7月2日0時0分的Date對象就可以了。
有一種情況是,可能我們的程序啟動的時候,已經(jīng)是2006年7月3日了,這樣的話,程序一啟動,定時任務(wù)就開始執(zhí)行了。
schedule最后一個重載的方法是
public void schedule(TimerTask task,Date firstTime,long period)
import java.util.*;
class Peng{
public static void main(String args[])
{ //Double[] num = { 45.1,45.2 };
List dlist=new ArrayList();
dlist.add(45.1);
dlist.add(45.2);
dlist.add(110.22);
Double max = (Double)dlist.get(0);
Double min = (Double)dlist.get(0);
for (int i = 0; i < dlist.size(); i++) {
if (min > (Double)dlist.get(i)) min = (Double)dlist.get(i);
if (max < (Double)dlist.get(i)) max = (Double)dlist.get(i);
}
System.out.println("max的值為" + max + "min的值為" + min);
}
}
public class StyleSearchAndReplace {
public static void main(String args[]) {
String statement = "The question as to whether the jab is"
+ " superior to the cross has been debated for some time in"
+ " boxing circles. However, it is my opinion that this"
+ " false dichotomy misses the point. I call your attention"
+ " to the fact that the best boxers often use a combination of"
+ " the two. I call your attention to the fact that Mohammed"
+ " Ali,the Greatest of the sport of boxing, used both. He had"
+ " a tremendous jab, yet used his cross effectively, often,"
+ " and well";
String newStmt = statement.replaceAll("The question as to whether",
"Whether");
newStmt = newStmt.replaceAll(" of the sport of boxing", "");
newStmt = newStmt.replaceAll("amount of success", "success");
newStmt = newStmt.replaceAll("However, it is my opinion that this",
"This");
newStmt = newStmt.replaceAll("a combination of the two", "both");
newStmt = newStmt.replaceAll("This is in spite of the fact that"
+ " the", "The");
newStmt = newStmt.replaceAll("I call your attention to the fact that",
"");
System.out.println("BEFORE:\n" + statement + "\n");
System.out.println("AFTER:\n" + newStmt);
}
}
//獲取yyyy-MM-dd是星期幾
public static int getWeekdayOfDateTime(String datetime){
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
try {
c.setTime(df.parse(datetime));
} catch (Exception e) {
e.printStackTrace();
}
int weekday = c.get(Calendar.DAY_OF_WEEK)-1;
return weekday;
}
package gmailsender;
import java.security.Security;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
* 使用Gmail發(fā)送郵件
* @author Winter Lau
*/
public class Main {
public static void main(String[] args) throws AddressException, MessagingException {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
// Get a Properties object
Properties props = System.getProperties();
props.setProperty("mail.smtp.host", "smtp.gmail.com");
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.put("mail.smtp.auth", "true");
final String username = "username";
final String password = "password";
Session session = Session.getDefaultInstance(props, new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}});
// -- Create a new message --
Message msg = new MimeMessage(session);
// -- Set the FROM and TO fields --
String[] gods={"dfgd@yahoo.com.cn","dfgdf@qq.com"};
int len=gods.length;
InternetAddress[] address = new InternetAddress[len];
for (int i = 0; i < gods.length; i++) {
address[i] = new InternetAddress(gods[i]);
}
msg.setFrom(new InternetAddress("fgdfgf@gmail.com"));
//msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse("dgddfg@qq.com",false));
msg.setRecipients(Message.RecipientType.TO,address);
msg.setSubject("woaizhongguo");
msg.setText("woaizhongguo");
msg.setSentDate(new Date());
Transport.send(msg);
System.out.println("郵件已發(fā)送!");
}
}
package gmailsender;
import java.security.Security;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
* 使用Gmail發(fā)送郵件
* @author Winter Lau
*/
public class Main {
public static void main(String[] args) throws AddressException, MessagingException {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
// Get a Properties object
Properties props = System.getProperties();
props.setProperty("mail.smtp.host", "smtp.gmail.com");
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.auth", "true");
final String username = "";
final String password = "";
Session session = Session.getDefaultInstance(props, new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}});
// -- Create a new message --
Message msg = new MimeMessage(session);
// -- Set the FROM and TO fields --
msg.setFrom(new InternetAddress(username + "@gmail.com"));
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("fuxuan1986@gmail.com",false));
msg.setSubject("Hello");
msg.setText("How are you");
msg.setSentDate(new Date());
Transport.send(msg);
System.out.println("Message sent.");
}
}