我的主要计划如下:
package priceCollector;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.text.DateFormat;
import java.util.Date;
public class App extends TimerTask {
public static void main(String[] args) {
Date now = new Date();
DateFormat df = DateFormat.getDateInstance();
String s = df.format(now);
String fileName = "/Users/Desktop/" + s + ".csv";
URL link = null;
try {
link = new URL("http://finance.yahoo.com/d/quotes.csv?s=III.L+ADM.L+AAL.L+ANTO.L+AHT.L+ABF.L+AZN.L+AV.L+BAB.L+BA.L+BARC.L+BDEV.L+BLT.L+BP.L+BATS.L+BLND.L+BTA.L+BNZL.L+BRBY.L+CPI.L+CCL.L+CNA.L+CCH.L+CPG.L+CRH.L+CRDA.L+DCC.L+DGE.L+DLG.L+DC.L+EZJ.L+EXPN.L+FRES.L+GKN.L+GSK.L+GLEN.L+HMSO.L+HL.L+HIK.L+HSBA.L+IMB.L+INF.L+IHG.L+IAG.L+ITRK.L+INTU.L+ITV.L+JMAT.L+KGF.L+LAND.L+LGEN.L+LLOY.L+LSE.L+MKS.L+MDC.L+MERL.L+MCRO.L+MNDI.L+MRW.L+NG.L+NXT.L+OML.L+PPB.L+PSON.L+PSN.L+POLY.L+PFG.L+PRU.L+RRS.L+RB.L+REL.L+RIO.L+RR.L+RBS.L+RDSA.L+RDSB.L+RMG.L+RSA.L+SGE.L+SBRY.L+SDR.L+SVT.L+SHP.L+SKY.L+SN.L+SMIN.L+SSE.L+STJ.L+STAN.L+SL.L+TW.L+TSCO.L+TPK.L+TUI.L+ULVR.L+UU.L+VOD.L+WTB.L+WOS.L+WPG.L+WPP.L&f=np");
InputStream in = new BufferedInputStream(link.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1!=(n=in.read(buf))){
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(response);
fos.close();
} catch (Exception e) {
System.out.println("not available");
}
}
}
单独运行时这样可以正常工作,但是我正在尝试设置一个定期的日程安排,这会使它每天都在运行。我的TimerTask程序是:
package priceCollector;
import java.util.Calendar;
import java.util.Timer;
import java.util.concurrent.TimeUnit;
public class TimerTask {
public void runTask(){
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 21);
calendar.set(Calendar.MINUTE, 15);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Timer time = new Timer(); // Instantiate Timer Object
// Start running the task on Thursday at 21:15:00, period is set to 1 day
// if you want to run the task immediately, set the 2nd parameter to 0
time.schedule(new App(), calendar.getTime(), TimeUnit.HOURS.toMillis(8));
}
}
最后一行(schedule参数)给出以下错误:
Timer类型中的方法调度(TimerTask,Date,long)不是 适用于参数(App,Date,long)
不确定这是什么。 Java新手!谢谢。
答案 0 :(得分:0)
第二个参数是初始延迟,如下面的API所示:
//Example, If you want to configure the initial delay as 5 seconds
time.schedule(new App(), 5000, TimeUnit.HOURS.toMillis(8));
public void schedule(TimerTask任务,长延迟,长时间)
任务 - 要安排的任务。
延迟 - 在执行任务之前以毫秒为单位的延迟。
时间段 - 连续任务执行之间的时间(以毫秒为单位)。