Home > Enterprise >  Keep running a second function in the background in Go
Keep running a second function in the background in Go

Time:02-18

I want to keep running a Function in the background while the program execute.

func sendTicket(userTickets uint, firstName string, lastName string, email string) {
    time.Sleep(20 * time.Second) //Simulate email delay
    var ticket = fmt.Sprintf("%v tickets for %v %v", userTickets, firstName, lastName)
    fmt.Println("\n")
    fmt.Println("*******************************************************")
    fmt.Printf("Sending Ticket:\n %v \nto email address %v\n ", ticket, email)
    fmt.Println("*******************************************************")
}

This is the function I want to keep running in the background. As it has a 20 second wait time, I want this function print out the message while the other functions are running.

CodePudding user response:

I think you are talking about concurrency. You can simply achieve this by typing go when you are calling this function. Like this,

package main

import "fmt"

func main() {        
    //function you want to "run in background"
    go sendTicket(userTickets, firstName, lastName, email)

    other functions...

}
  •  Tags:  
  • go
  • Related