有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java计划每天运行2次的任务

我想在一天中的早上8:30和晚上2:30删除一个文件夹中的所有文件。 它应该只永久删除所有文件,而不删除文件夹

我的删除代码运行正常,但我在计划方面遇到问题。我不知道如何编写调度程序。有谁能帮我用正确的代码来安排吗

public class Delete 
{ 
    public static void main(String[] args) 
    { 
        try
        { 
            Files.deleteIfExists(Paths.get("C:\\Users\\Dekstop\\Dummy")); 
//I want to delete all Files not the Folder
        } 
        catch(NoSuchFileException e) 
        { 
            System.out.println("No such file/directory exists"); 
        } 
        catch(DirectoryNotEmptyException e) 
        { 
            System.out.println("Directory is not empty."); 
        } 
        catch(IOException e) 
        { 
            System.out.println("Invalid permissions."); 
        } 

        System.out.println("Deletion successful."); 
    } 
} 

共 (2) 个答案

  1. # 1 楼答案

    继续这个Original post

    public class ExecuteTimer {
      public static void main(String[] args){
           MyTimer te1=new MyTimer("My_Task1");
           MyTimer te2=new MyTimer("My_Task2");
          Timer t=new Timer();
          t.scheduleAtFixedRate(te1, 0,5*1000);
          t.scheduleAtFixedRate(te2, 0,1000);
       }
    }
    

    我的计时器。阶级

    public class MyTimer extends TimerTask{
    private String timername ;
    public MyTimer(String n){
      this.timername=n;
    }
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+" "+name+" the task has executed successfully "+ new Date());
        if("Task1".equalsIgnoreCase(name)){
          try {
          Thread.sleep(10000);
          } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
    }
    }
    
  2. # 2 楼答案

    您可以使用计时器。计划(TimerTask任务、首次日期、长周期)方法

    将首次时间设置为上午(任何时间),并将时段设置为12小时即可完成此工作