我有一个关于计时器功能的问题。我已经设法找到问题的原因,但我不确定如何解决它。我将向您概述我的职能。它将首先执行 cost() 函数,并有一个后台线程工作。然而,我意识到我的 cost() 函数一开始就无法加载。其次,它的程序每 60 秒运行一次,但也失败了。我检查了我的 cost() 函数的代码,如果我在没有计时器函数的情况下调用它,它工作得很好。这可能是我的 Opencsv() 函数吗?问题是由于定时器功能的限制还是有办法解决这个问题?
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 {
}
}
最佳答案
我真的认为你的“bug”不在这里,而是在其他地方。另外你应该认真看看
ScheduledThreadPoolExecutor
而不是计时器,它会是这样的:
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
executor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
//Do your stuff in here
}
}), 60, TimeUnit.SECONDS );
另外,我建议不要吞下 InterruptedExceptions - 这里有很多关于这个主题的帖子。
干杯, 尤金。
关于java - 定时器功能未运行。 java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8912782/