2014-11-23 17 views
-2

我正在寫一個代碼,將在上午8點打開一個網頁。我計劃在我離開學校之前(大約早上6:30)發起這段代碼,並閱讀我回家後(大約下午3:30)打開的頁面。在我的代碼示例中,我將YouTube作爲以保持我打算開放的網頁的完整性。然而,我一直在嘗試幾個小時,但沒有運氣讓這段代碼工作。我對Java語言知之甚少(這是我的一個巨大錯誤),我很快就需要使用這些代碼。請幫幫我!網頁定時開啓器不工作(爪哇)

編輯:我不知道哪部分代碼失敗。當我在Eclipse控制檯中運行它時,它不顯示錯誤,只是不起作用。因此,要回答任何這樣的問題,我不確定哪些不起作用。

import java.awt.Desktop; 
import java.io.IOException; 
import java.net.URI; 
import java.net.URISyntaxException; 
import java.util.Calendar; 
import java.util.Timer; 
import java.util.TimerTask; 

public class Browser { 
    public static void main(String[] args) throws InterruptedException { 
     while(true) { 
      Timer timer = new Timer(); 
      TimerTask tt = new TimerTask(){ 
       public void run(){ 
        Calendar cal = Calendar.getInstance(); //this is the method you should use, not the Date(), because it is depreciated. 

        int hour = cal.get(Calendar.HOUR_OF_DAY);//get the hour number of the day, from 0 to 23 

        if(hour == 8){ 
         String url = "http://www.youtube.com"; 

         if(Desktop.isDesktopSupported()){ 
          Desktop desktop = Desktop.getDesktop(); 
          try { 
           desktop.browse(new URI(url)); 
          } catch (IOException | URISyntaxException e) { 
           // TODO Auto-generated catch block 
           e.printStackTrace(); 
          } 
         } else { 
          Runtime runtime = Runtime.getRuntime(); 
          try { 
           runtime.exec("xdg-open " + url); 
          } catch (IOException e) { 
           // TODO Auto-generated catch block 
           e.printStackTrace(); 
          } 
         } 
        } 
       } 
      }; 
      Thread.sleep(1000); 
     } 
    } 
} 
+1

究竟什麼是你的問題嗎?不讓你的代碼工作有點含糊,哪部分失敗? – t0mppa 2014-11-23 22:09:36

回答

0

你永遠不安排TimerTask的tt

public static void main(String[] args) throws InterruptedException { 
    Timer timer = new Timer(); 
    TimerTask tt = new TimerTask() { 
     public void run() { 
      Calendar cal = Calendar.getInstance(); 
      int hour = cal.get(Calendar.HOUR_OF_DAY); 
      if(hour == 8) { 
       String url = "http://www.youtube.com"; 
       if(Desktop.isDesktopSupported()){ 
        Desktop desktop = Desktop.getDesktop(); 
        try { 
         desktop.browse(new URI(url)); 
        } catch (IOException | URISyntaxException e) { 
         e.printStackTrace(); 
        } 
       } else { 
        Runtime runtime = Runtime.getRuntime(); 
        try { 
         runtime.exec("xdg-open " + url); 
        } catch (IOException e) { 
         e.printStackTrace(); 
        } 
       } 
      } 
     } 
    }; 
    timer.schedule(tt, 0, 1000); 
} 
+0

非常感謝你!這使我的代碼工作!但是在我這樣做後,我只希望它打開一個網頁。我如何在一次之後停止它? – SquidThePrinter 2014-11-23 23:11:24

+0

如果您只想在上午8:00正好打開一次網頁,那麼您應該檢查小時,分鐘和秒鐘是否是您想要的。不知道你的用例,很難理解你的需求。 – irrelephant 2014-11-23 23:31:01

+0

我不確定「用例」是什麼意思。 – SquidThePrinter 2014-11-23 23:49:35