-2

The following PHP code that allows a process to only run between certain times. How would this be done in GoLang?

$curdate = date('Y-m-d');
$mydate=getdate(strtotime($curdate));
if ( $mydate['wday'] === 0 ) {
  if ( date('H') < 15 ) { exit; }; // This is for 0 Sunday!!!
}
if ( $mydate['wday'] === 5 ) {
  if ( date('H') > 19 ) { exit; }; // This is for 5 Friday!!!
}
if ( $mydate['wday'] === 6 ) {
  exit;  // This is for 6 Saturday //
}
Bassie
  • 9,529
  • 8
  • 68
  • 159

2 Answers2

4

This should do the same thing:

now := time.Now()
day := now.Weekday()
hr  := now.Hour()

if day == 0 {
    if hr < 15 { os.Exit(0) }
} 
if day == 5 {
    if hr > 19 { os.Exit(0) }
}
if day == 6 {
    os.Exit(0)
}

Where similarly, each day can be represented by an integer (0 - 6).

Note that to use time and os you will need to call

import "time"
import "os"

See the documentation for more about Golang time.

Bassie
  • 9,529
  • 8
  • 68
  • 159
  • In go how would you verify the process is already running if it called to start? So the process would not have more than one running instance? – user2777145 May 07 '17 at 19:10
  • @user2777145 Sorry but you will have to do some research or ask a seperate question as I don't know – Bassie May 07 '17 at 19:12
  • No problem my fix is to ps | grep for process before starting process to verify it is not running. – user2777145 May 07 '17 at 19:20
0

Don't write PHP code as Go code. Write Go code. For example,

package main

import (
    "os"
    "time"
)

func main() {
    now := time.Now()
    hour := now.Hour()
    switch now.Weekday() {
    case time.Sunday:
        if hour < 15 {
            os.Exit(0)
        }
    case time.Friday:
        if hour > 19 {
            os.Exit(0)
        }
    case time.Saturday:
        os.Exit(0)
    }
    // Do Something
}
peterSO
  • 158,998
  • 31
  • 281
  • 276
  • I am in a loop till I hit the other side of the date/time. So I haft to call time.now and then do a test of either switch / case or if. Not sure which would be the best way togo. switch / case is faster than several if in the main function of go. – user2777145 May 07 '17 at 20:10