以下是我的计划。我想在它上面使用ExecutorService
每天运行一次。但是,该计划不是“可以运行的”。请提出必要的修改建议。
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 myTimerTask {
public static void main(String[] args) {
Date now = new Date();
DateFormat df = DateFormat.getDateInstance();
String s = df.format(now);
String fileName = new 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");
}
}
}
我猜你需要实现run()
实例,但不确定如何编写程序。
答案 0 :(得分:0)
您需要按照以下步骤使用ScheduledExecutorService
,如下所示:
步骤(1):您需要将代码移到单独的类中,如下所示:
public TaskRunner implements Runnable {
public void run() {
//your code here (logic froom main method)
}
}
步骤(2):现在使用ScheduledExecutorService
,如下所示:
public class MySchduler {
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public static void main(String[] args) {
scheduler.scheduleAtFixedRate(new TaskRunner(), 0, 1, TimeUnit.DAYS);
}
}
您可以查看here