代码之家  ›  专栏  ›  技术社区  ›  Amadou Beye

每周创建一个文件

  •  1
  • Amadou Beye  · 技术社区  · 6 年前

    我有一个Java程序,每天都要手动运行。 现在我想为每个wek创建一个excel文件,在其中写入本周的所有任务

    我知道如何每天创建这样的文件:

    if(!IoUtils.fileExist("indicators-" + IoUtils.getCurrentDate() + ".xls")){
        IoUtils.createIndicFile("indicators-" + IoUtils.getCurrentDate() + ".xls");
    }
    else IoUtils.INDIC_FILEPATH = "indicators-" + IoUtils.getCurrentDate() + ".xls";
    

    以下是以特定格式提供当前日期的函数:

    // IoUtils class
    public static String getCurrentDate(){
        LocalDateTime ldt = LocalDateTime.now();
        return DateTimeFormatter.ofPattern("dd-MM-yyyy", Locale.ENGLISH).format(ldt);
    }
    

    那么,我如何才能将此更改为每周仅创建一个文件?

    我还希望文件名中包含月份和周数,如下所示:

    // first monday of january 2018
    name = "indicators-week1-01-2018"
    
    // second monday of january 2018
    name = "indicators-week2-01-2018"
    

    谢谢你

    7 回复  |  直到 6 年前
        1
  •  1
  •   Vebbie    6 年前

    Java提供 java.util.concurrent.scheduledThreadPoolExecutor 它还可以安排命令在给定的延迟后运行,或定期执行。

    Scheduler.scheduleWithFixedDelay(task, StartDelay, repeatInterval, TimeUnit.MINUTES);
    
        2
  •  1
  •   Basil Bourque    6 年前

    遗嘱执行人

    旧的学校方式 Timer 班级。

    新的学校方式使用 Executors framework 它处理在后台线程上调度任务的细节。

    设置一个执行器来运行 Runnable 每隔几个小时。这个任务检查当前时刻。如果当前日期的星期一是星期一,并且您的文件尚未写入,请将其写入。如果没有,那么让runnable过期。这个 scheduled executor service 将在几个小时后再次运行,并重复一次又一次。

    第一步是获取当前日期。

    时区对确定日期至关重要。在任何一个特定的时刻,日期都会因地区而异。例如,在午夜几分钟后 Paris France 是新的一天,而昨天还在 Montréal Québec .

    如果未指定时区,jvm将隐式应用其当前默认时区。违约可能 change at any moment 运行时(!),所以结果可能会有所不同。最好指定 desired/expected time zone 显式地作为参数。

    指定一个 proper time zone name 格式为 continent/region ,如 America/Montreal , Africa/Casablanca Pacific/Auckland . 切勿使用2-4个字母的缩写,如 EST IST 因为它们是 真正的时区,不标准,甚至不唯一(!).

    ZoneId z = ZoneId.of( "America/Montreal" ) ;
    LocalDate today = LocalDate.now( z );
    

    从那得到一周的当前日期。

    DayOfWeek dow = today.getDayOfWeek() ;
    

    如果今天是星期一,那么看看文件是否已被写入。如果没有,写下来。

    if( dow.equals( DayOfWeek.MONDAY ) ) {
        if( file not written ) { write file }
    }
    

    把所有这些放在一个命名方法中。

    private void writeFileOnMonday ( ) {
        ZoneId z = ZoneId.of( "America/Montreal" );
        LocalDate today = LocalDate.now( z );
        DayOfWeek dow = today.getDayOfWeek();
        if ( dow.equals( DayOfWeek.MONDAY ) ) {
            if ( file not written ){ write file }
        }
    }
    

    在一个 预定执行人服务 . 指定两次运行之间的等待时间。如果我们指定每3小时运行一次任务,那么,逻辑指示,我们的每周文件将在每周一午夜到凌晨3点之间的某个时间写入。

    调度执行器服务的一个大问题是:如果在运行 Throwable ( Exception Error )被你的任务抛出,并到达执行者。所以总是把你的任务放在试一试。见 this Question .

    ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();  // Convenience method to produce an executor service.
    
    ScheduledFuture scheduledFuture =          // A handle to check the status of your task. May or may not be useful to you.
            scheduledExecutorService
                    .scheduleWithFixedDelay( new Runnable() {  // Implement the `Runnable` interface as your task. 
                                                 @Override
                                                 public void run ( ) {
                                                     try {
                                                         writeFileOnMonday();
                                                     } catch (Exception e ) {
                                                         … handle unexected exception
                                                     }
                                                 }
                                             } ,
                            0 ,                 // Initial delay
                            3 ,                 // Delay between runs.
                            TimeUnit.HOURS );   // Unit of time meant for the pair of delay numbers above.
    

    搜索堆栈溢出以获取更多信息,因为所有这些都已被多次覆盖。


    关于 Java.时间

    这个 java.time 框架是在Java 8和之后构建的。这些类取代了麻烦的旧类 legacy 日期时间类,如 java.util.Date , Calendar 和; SimpleDateFormat .

    这个 Joda-Time 项目,现在在 maintenance mode ,建议迁移到 java.time 类。

    要了解更多信息,请参阅 Oracle Tutorial . 和搜索堆栈溢出的许多例子和解释。规格是 JSR 310 .

    你可以交换 Java.时间 直接使用数据库的对象。使用 JDBC driver 符合 JDBC 4.2 或稍后。不需要弦,不需要 java.sql.* 类。

    在哪里获得java.time类?

    这个 ThreeTen-Extra project使用其他类扩展java.time。这个项目是将来可能添加java.time的一个试验场。你可以在这里找到一些有用的类,比如 Interval , YearWeek , YearQuarter more .

        3
  •  0
  •   salz    6 年前

    创建quartz cron作业调度程序 0 0 12 ? * MON . 这将把工作安排在每周一下午12点。

        4
  •  0
  •   Samuel Kok    6 年前

    因为你在使用 LocalDateTime ,您可以使用 getDayOfWeek 方法。

    例如

    if(LocalDateTime.now().getDayOfWeek() == DayOfWeek.MONDAY){
      // File Creation Logic ...
    }    
    
        5
  •  0
  •   himanshu agarwal    6 年前

    使用Calender API,calendar.get(calendar.day_of_week)将返回周一的int 2。

    import java.util.Calendar;
    
    if(calendar.get(Calendar.DAY_OF_WEEK) == 2)
      if(!IoUtils.fileExist("indicators-" + IoUtils.getCurrentDate() + ".xls")){
          IoUtils.createIndicFile("indicators-" + IoUtils.getCurrentDate() + ".xls");
      }
      else IoUtils.INDIC_FILEPATH = "indicators-" + IoUtils.getCurrentDate() + ".xls";
    
        6
  •  0
  •   hunter    6 年前
    Calendar cal = Calendar.getInstance();
    cal.setFirstDayOfWeek(Calendar.MONDAY);
    int week = cal.get(Calendar.WEEK_OF_YEAR);
    
    String expectedFileName = "indicators-week"+week+"-whateveryouwant-"+cal.get(Calendar.YEAR);
    

    然后,您可以检查文件是否存在,写入同一文件,如果文件不存在,您将使用预期的文件名创建一个新文件并写入该新文件。但根据要求,应正确处理年假

        7
  •  0
  •   Saeed Hassanvand    6 年前

    使用 Calendar :

    Calendar cal = Calendar.getInstance();
    int currentDay = cal.get(Calendar.DAY_OF_WEEK); 
    if (currentDay == Calendar.MONDAY) {
        // write your code here
    }