我的AsyncTask中有一个输入流 - 它来自一个带有retrieveFileStream方法的FTP服务器,只包含一行 - 我想定期读取同一个文件,就像每30秒一样。我只能阅读一次文件,但我不知道如何定期这样做。以下是我的代码的一部分:
ftpClient.connect("f11-preview.125mb.com", 21);
System.out.println(ftpClient.getReplyString());
ftpClient.enterLocalPassiveMode();
System.out.println(ftpClient.getReplyString());
ftpClient.sendCommand(FTPCmd.USER, "xxx");
System.out.println(ftpClient.getReplyString());
ftpClient.sendCommand(FTPCmd.PASS, "yyy");
System.out.println(ftpClient.getReplyString());
ftpClient.sendCommand(FTPCmd.CWD, "/CodeJava");
System.out.println(ftpClient.getReplyString());
// that part of the code i want to do periodically :
InputStream is= (ftpClient.retrieveFileStream("deneme1.txt"));
System.out.println("Input Stream has opened.");
StringWriter writer = new StringWriter();
IOUtils.copy(is, writer, "UTF-8");
theString = writer.toString();
System.out.println(theString);
答案 0 :(得分:2)
您可以使用计时器:
new Timer().scheduleAtFixedRate(new TimerTask(){
@Override
public void run() {
//Your task here
}
}, 0, 30 * 1000);
您也可以使用Tony指出的SchelduledExcutorService
您可以在此处阅读相关内容:http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html
或
这里:https://gist.github.com/codingtony/c21e278b3111d5256f0d