我有一個關於定時器功能的問題。我設法找到了我的問題的原因,但我不確定如何解決它。我會給你一個我的功能的概述。它將首先執行cost()函數,後臺線程正常工作。但是,我意識到我的cost()函數在開始時無法正確加載。其次,它是每60秒運行一次的程序,它也是失敗的。我檢查我的代碼以獲取我的cost()函數,如果我不使用定時器函數調用它,它會正常工作。它可以是我的Opencsv()函數嗎?問題是由於計時器功能的限制,還是有辦法解決這個問題?定時器功能未運行。 Java
public static void main(String[] args) {
launch(EVschedulerApp.class, args);
Timer timer = new Timer();
// timer.scheduleAtFixedRate(new Cost(), 10*1000, 10*1000);
timer.scheduleAtFixedRate(new Cost() {
@Override
public void run() {
new Thread(new Runnable() {
public void run() {
File file = new File("D:/test.csv");
if(file != null){
try {
Opencsv csv = new Opencsv();
csv.Csvreader();
} catch (IOException ex) {
Logger.getLogger(EVschedulerApp.class.getName()).log(Level.SEVERE, null, ex);
}
}
else {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
}
}
}).start();
}
Opencsv類文件:
public class Opencsv {
public void Csvreader() throws IOException {
try {
// TODO code application logic here
CSVReader reader = new CSVReader(new FileReader("D:/Test.csv"));
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
System.out.println(nextLine[0] + " " + nextLine[1]+ " " + nextLine[2]+ " " + nextLine[3]);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(Opencsv.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
成本類:
public class Cost extends TimerTask{
public void run() {
Calendar rightNow = Calendar.getInstance();
Integer hour = rightNow.get(Calendar.HOUR_OF_DAY);
if (hour==23) {
try {
URL tariff = new URL("http://www.******.downloadRealtime=true");
ReadableByteChannel tar = Channels.newChannel(Test.openStream());
FileOutputStream fos = new FileOutputStream("Test.csv");
fos.getChannel().transferFrom(tar, 0, 1<<24);
} catch (IOException ex) {
Logger.getLogger(Cost.class.getName()).log(Level.SEVERE, null, ex);
}
}
else {
}
}
我添加了super.run(),但它沒有工作,我會嘗試執行程序服務 – Eugene 2012-01-18 16:19:41