关于定时任务,似乎跟时间操作的联系并不是很大,但是前面既然提到了定时任务,索性在这里一起解决了。
设置定时任务很简单,用Timer类就搞定了。
一、延时执行
首先,我们定义一个类,给它取个名字叫TimeTask,我们的定时任务,就在这个类的main函数里执行。代码如下:
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);
}
}
解释一下上面的代码。
上面的代码实现了这样一个功能,当TimeTask程序启动以后,过一分钟后执行某项任务。很简单吧:先new一个Timer对象,然后调用它的schedule方法,这个方法有四个重载的方法,这里我们用其中一个,
public void schedule(TimerTask task,long delay)
首先,第一个参数
第一个参数就是我们要执行的任务。
这是一个TimerTask对象,确切点说是一个实现TimerTask的类的对象,因为TimerTask是个抽象类。上面的代码里面,Task就是我们自己定义的实现了TimerTask的类,因为是在同一个包里面,所以没有显性的import进来。Task类的代码如下
package test;
import java.util.TimerTask;
public class Task extends TimerTask {
public void run(){
System.out.println("定时任务执行");
}
}
我们的Task必须实现TimerTask的方法run,要执行的任务就在这个run方法里面,这里,我们只让它往控制台打一行字。
第二个参数
第二个参数是一个long型的值。这是延迟的时间,就是从程序开始以后,再过多少时间来执行定时任务。这个long型的值是毫秒数,所以前面我们的程序里面,过一分钟后执行用的参数值就是 60 * 1000。
二、循环执行
设置定时任务的时候,往往我们需要重复的执行这样任务,每隔一段时间执行一次,而上面的方法是只执行一次的,这样就用到了schedule方法的是另一个重载函数
public void schedule(TimerTask task,long delay,long period)
前两个参数就不用说什么了,最后一个参数就是间隔的时间,又是个long型的毫秒数(看来java里涉及到时间的,跟这个long是脱不了干系了),比如我们希望上面的任务从第一次执行后,每个一分钟执行一次,第三个参数值赋60 * 1000就ok了。
三、指定执行时间
既然号称是定时任务,我们肯定希望由我们来指定任务指定的时间,显然上面的方法就不中用了,因为我们不知道程序什么时间开始运行,就没办法确定需要延时多少。没关系,schedule四个重载的方法还没用完呢。用下面这个就OK了:
public void schedule(TimerTask task,Date time)
比如,我们希望定时任务2006年7月2日0时0分执行,只要给第二个参数传一个时间设置为2006年7月2日0时0分的Date对象就可以了。
有一种情况是,可能我们的程序启动的时候,已经是2006年7月3日了,这样的话,程序一启动,定时任务就开始执行了。
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发送邮件
* @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("邮件已发送!");
}
}
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发送邮件
* @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.");
}
}