builtbyphillip
HOBBYOP
6 months ago
I am very new to setting up an API. I have sucessfully built a working API that has been tested with Postman. How do I run a particular method with Railway every hour? My router for the specific endpoint I want to call every hour looks like this: router.POST("/alerts/run", handlers.CheckFlights)
8 Replies
adam
MODERATOR
6 months ago
You'll have to create another service who's sole purpose is to call that endpoint. Then using Railway Cron, schedule it to run at a specific frequency
adam
MODERATOR
6 months ago
Code it!
adam
MODERATOR
6 months ago
Unless you can find a way to run what you need using just a bash command
if you want to use only one instance, you can use code like this
// main.go
package main
import (
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
// This is the function you want to run every hour
func CheckFlights() {
// Replace this with your actual logic
fmt.Println("CheckFlights executed at:", time.Now().Format(time.RFC3339))
}
// This function starts a scheduler in a goroutine
func StartScheduler(interval time.Duration, stopChan <-chan struct{}) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
// Run the job concurrently
go CheckFlights()
case <-stopChan:
fmt.Println("Scheduler stopped.")
return
}
}
}
func main() {
// Channel to gracefully stop the scheduler
stopChan := make(chan struct{})
// Start the scheduler in the background (every 1 hour)
go StartScheduler(1*time.Hour, stopChan)
// For demo/testing, you can use a shorter interval, e.g. 10 seconds:
// go StartScheduler(10*time.Second, stopChan)
// HTTP endpoint to trigger the job manually
http.HandleFunc("/alerts/run", func(w http.ResponseWriter, r *http.Request) {
CheckFlights()
w.Write([]byte("CheckFlights executed manually"))
})
// Graceful shutdown: catch Ctrl+C (SIGINT/SIGTERM)
go func() {
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
<-sigChan
close(stopChan)
os.Exit(0)
}()
fmt.Println("Server running at :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}adam
MODERATOR
6 months ago
!s
Status changed to Solved adam • 6 months ago