Keep running a second function in the background in Go


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.Printf("Sending Ticket:\n %v \nto email address %v\n ", ticket, email)

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.


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...


Answered By – Kaweendra

Answer Checked By – Marilyn (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.