2

I created a program that is running daily at a certain time,

but I want this program to stop at some particular days(week ends),

I have used the below codes to set the current time,

public int GetDateNow()
{
    Calendar currentdate = Calendar.getInstance();
    DateFormat dateformat = new SimpleDateFormat("HHmm");
    String datenow = dateformat.format(currentdate.getTime());
    int DN=Integer.parseInt(datenow);
    return DN;
}    

and the below code in the main class

while(true)
{
    Thread.sleep(1*1000);
    if(gt.GetDateNow()==0000)
    {
        //perform action
    }
}
Wojciech Wirzbicki
  • 3,887
  • 6
  • 36
  • 59
sofian
  • 157
  • 2
  • 3
  • 7
  • 2
    -1 It's the [first result](http://www.google.com/search?q=java%20get%20week%20day)... – Anko - inactive in protest Dec 17 '12 at 18:36
  • FYI, the terribly troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Oct 01 '18 at 00:37

3 Answers3

8

Use Calendar

calendarInstance.get(Calendar.DAY_OF_WEEK);

and compare it against weekends (Calendar.SATURDAY, Calendar.SUNDAY or depending on country)

jmj
  • 237,923
  • 42
  • 401
  • 438
  • +1 Also, besides from comparing it, remember that the days range from 1 to 7 being `SUNDAY == 1` and `SATURDAY == 7`. – Fritz Dec 17 '12 at 18:32
  • I tried your code but still it is not working, I did not know what to put in the (if statement in the main class) – sofian Dec 17 '12 at 20:55
  • what did you try and that not worked, could you please update your post with code – jmj Dec 17 '12 at 20:57
0

Spring Framework provides scheduling of tasks based on cron expressions, all you need is to configure your tasks in context.xml e.g.

<task:scheduled ref="task" method="execute" cron="* 15 9-17 * * MON-FRI" />
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
0

OK, thanks guys it is working fine after I used the codes

calendarInstance.get(Calendar.DAY_OF_WEEK);

all bests,

sofian
  • 157
  • 2
  • 3
  • 7