84 lines
1.8 KiB
Go
84 lines
1.8 KiB
Go
package cmd
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"os/signal"
|
|
"syscall"
|
|
"time"
|
|
|
|
"axis_timelapse/camera"
|
|
"axis_timelapse/config"
|
|
|
|
"github.com/go-co-op/gocron/v2"
|
|
"github.com/rs/zerolog/log"
|
|
"github.com/spf13/cobra"
|
|
)
|
|
|
|
var rootCommand = &cobra.Command{
|
|
Use: "axis_timelapse",
|
|
Short: "Runs the axis_timelapse daemon.",
|
|
PreRun: func(cmd *cobra.Command, args []string) {
|
|
config.GetConfig()
|
|
config.GenerateFullURL()
|
|
},
|
|
Run: func(cmd *cobra.Command, args []string) {
|
|
startTasks()
|
|
},
|
|
}
|
|
|
|
var versionCommand = &cobra.Command{
|
|
Use: "version",
|
|
Short: "Prints the current executable version and exits.",
|
|
Run: func(cmd *cobra.Command, _ []string) {
|
|
fmt.Printf("%s | Version: %s Build: %s | Copyright © %d William Gill\n", config.Project, config.Version, config.Build, time.Now().Year())
|
|
},
|
|
}
|
|
|
|
func Execute() {
|
|
if err := rootCommand.Execute(); err != nil {
|
|
log.Fatal().Err(err).Msgf("failed to execute command.")
|
|
}
|
|
}
|
|
|
|
func init() {
|
|
rootCommand.PersistentFlags().StringVarP(&config.TOML, "config", "c", "config.toml", "Specify daemon config file.")
|
|
rootCommand.AddCommand(versionCommand)
|
|
}
|
|
|
|
func startTasks() {
|
|
// Create a new scheduler
|
|
s, err := gocron.NewScheduler()
|
|
if err != nil {
|
|
log.Fatal().Err(err).Msgf("")
|
|
}
|
|
|
|
// Schedule the job
|
|
_, err = s.NewJob(
|
|
gocron.CronJob(config.CaptureChron, false),
|
|
gocron.NewTask(func() {
|
|
camera.CaptureImage()
|
|
}),
|
|
)
|
|
if err != nil {
|
|
log.Fatal().Err(err).Msgf("")
|
|
}
|
|
|
|
// Start the scheduler
|
|
s.Start()
|
|
|
|
// Set up signal handling for graceful shutdown
|
|
sigChan := make(chan os.Signal, 1)
|
|
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
|
|
|
|
// Wait for interrupt signal
|
|
<-sigChan
|
|
log.Info().Msg("Received interrupt signal, shutting down gracefully...")
|
|
|
|
// Shutdown the scheduler gracefully
|
|
err = s.Shutdown()
|
|
if err != nil {
|
|
log.Fatal().Err(err).Msgf("Error during shutdown.")
|
|
}
|
|
}
|