How to use Get method of cronjob Package

Best Testkube code snippet using cronjob.Get

cronjob_controller.go

Source:cronjob_controller.go Github

copy

Full Screen

...66func (r *CronJobReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {67 log := log.FromContext(ctx)68 // Load the CronJob by name69 var cronJob batchv1.CronJob70 if err := r.Get(ctx, req.NamespacedName, &cronJob); err != nil {71 log.Error(err, "unable to fetch CronJob")72 // we'll ignore not-found errors, since they can't be fixed by an immediate73 // requeue (we'll need to wait for a new notification), and we can get them74 // on deleted requests.75 return ctrl.Result{}, client.IgnoreNotFound(err)76 }77 // List all active jobs, and log the status78 var childJobs kbatch.JobList79 if err := r.List(ctx, &childJobs, client.InNamespace(req.Namespace), client.MatchingFields{jobOwnerKey: req.Name}); err != nil {80 log.Error(err, "unable to list child Jobs")81 return ctrl.Result{}, err82 }83 // Find the active list of jobs84 // Status should be able to be reconstituted from the state of the world, so it’s generally not a good idea to read85 // from the status of the root object. Instead, you should reconstruct it every run86 var activeJobs []*kbatch.Job87 var successfulJobs []*kbatch.Job88 var failedJobs []*kbatch.Job89 var mostRecentTime *time.Time90 isJobFinished := func(job *kbatch.Job) (bool, kbatch.JobConditionType) {91 for _, c := range job.Status.Conditions {92 if (c.Type == kbatch.JobComplete || c.Type == kbatch.JobFailed) && c.Status == corev1.ConditionTrue {93 return true, c.Type94 }95 }96 return false, ""97 }98 getScheduledTimeForJob := func(job *kbatch.Job) (*time.Time, error) {99 timeRaw := job.Annotations[scheduledTimeAnnotation]100 if len(timeRaw) == 0 {101 return nil, nil102 }103 timeParsed, err := time.Parse(time.RFC3339, timeRaw)104 if err != nil {105 return nil, err106 }107 return &timeParsed, nil108 }109 for i, job := range childJobs.Items {110 _, finishedType := isJobFinished(&job)111 switch finishedType {112 case "": // ongoing113 activeJobs = append(activeJobs, &childJobs.Items[i])114 case kbatch.JobFailed:115 failedJobs = append(failedJobs, &childJobs.Items[i])116 case kbatch.JobComplete:117 successfulJobs = append(successfulJobs, &childJobs.Items[i])118 }119 // We'll store the launch time in an annotation, so we'll reconstitute that from120 // the active jobs themselves.121 scheduledTimeForJob, err := getScheduledTimeForJob(&job)122 if err != nil {123 log.Error(err, "unable to parse schedule time for child job", "job", &job)124 continue125 }126 if scheduledTimeForJob != nil {127 if mostRecentTime == nil {128 mostRecentTime = scheduledTimeForJob129 } else if mostRecentTime.Before(*scheduledTimeForJob) {130 mostRecentTime = scheduledTimeForJob131 }132 }133 }134 if mostRecentTime != nil {135 cronJob.Status.LastScheduleTime = &metav1.Time{Time: *mostRecentTime}136 } else {137 cronJob.Status.LastScheduleTime = nil138 }139 cronJob.Status.Active = nil140 for _, activeJob := range activeJobs {141 jobRef, err := ref.GetReference(r.Scheme, activeJob)142 if err != nil {143 log.Error(err, "unable to make reference to active job", "job", activeJob)144 continue145 }146 cronJob.Status.Active = append(cronJob.Status.Active, *jobRef)147 }148 // log how many jobs we observed at a slightly higher logging level149 log.V(1).Info("job count", "active jobs", len(activeJobs), "successful jobs", len(successfulJobs), "failed jobs", len(failedJobs))150 // Using the date we've gathered, we'll update the status of our CRD.151 if err := r.Status().Update(ctx, &cronJob); err != nil {152 log.Error(err, "unable to update CronJob status")153 return ctrl.Result{}, err154 }155 // Clean up old jobs156 if cronJob.Spec.FailedJobsHistoryLimit != nil {157 sort.Slice(failedJobs, func(i, j int) bool {158 if failedJobs[i].Status.StartTime == nil {159 return failedJobs[j].Status.StartTime != nil160 }161 return failedJobs[i].Status.StartTime.Before(failedJobs[j].Status.StartTime)162 })163 for i, job := range failedJobs {164 if int32(i) >= int32(len(failedJobs))-*cronJob.Spec.FailedJobsHistoryLimit {165 break166 }167 if err := r.Delete(ctx, job, client.PropagationPolicy(metav1.DeletePropagationBackground)); client.IgnoreNotFound(err) != nil {168 log.Error(err, "unable to delete old failed job", "job", job)169 } else {170 log.V(0).Info("deleted old failed job", "job", job)171 }172 }173 }174 if cronJob.Spec.SuccessfulJobHistoryLimit != nil {175 sort.Slice(successfulJobs, func(i, j int) bool {176 if successfulJobs[i].Status.StartTime == nil {177 return successfulJobs[j].Status.StartTime != nil178 }179 return successfulJobs[i].Status.StartTime.Before(successfulJobs[j].Status.StartTime)180 })181 for i, job := range successfulJobs {182 if int32(i) >= int32(len(successfulJobs))-*cronJob.Spec.SuccessfulJobHistoryLimit {183 break184 }185 if err := r.Delete(ctx, job, client.PropagationPolicy(metav1.DeletePropagationBackground)); (err) != nil {186 log.Error(err, "unable to delete old successful job", "job", job)187 } else {188 log.V(0).Info("deleted old successful job", "job", job)189 }190 }191 }192 // Check if we're suspended193 if cronJob.Spec.Suspend != nil && *cronJob.Spec.Suspend {194 log.V(1).Info("cronjob suspended, skipping")195 return ctrl.Result{}, nil196 }197 // Get the next scheduled run198 // Calculate the next scheduled time199 getNextSchedule := func(cronJob *batchv1.CronJob, now time.Time) (lastMissed time.Time, next time.Time, err error) {200 sched, err := cron.ParseStandard(cronJob.Spec.Schedule)201 if err != nil {202 return time.Time{}, time.Time{}, fmt.Errorf("Unparseable schedule %q: %v", cronJob.Spec.Schedule, err)203 }204 var earliestTime time.Time205 if cronJob.Status.LastScheduleTime != nil {206 earliestTime = cronJob.Status.LastScheduleTime.Time207 } else {208 earliestTime = cronJob.ObjectMeta.CreationTimestamp.Time209 }210 if cronJob.Spec.StartingDeadlineSeconds != nil {211 // controller is not going to schedule anything below this point212 schedulingDeadline := now.Add(-time.Second * time.Duration(*cronJob.Spec.StartingDeadlineSeconds))213 if schedulingDeadline.After(earliestTime) {214 earliestTime = schedulingDeadline215 }216 }217 if earliestTime.After(now) {218 return time.Time{}, sched.Next(now), nil219 }220 starts := 0221 for t := sched.Next(earliestTime); !t.After(now); t = sched.Next(t) {222 lastMissed = t223 starts++224 if starts > 100 {225 // We can't get the most recent times so just return an empty slice226 return time.Time{}, time.Time{}, fmt.Errorf("too many missed start times (> 100). Set or decrease .spec.startingDeadlineSeconds or check clock skew")227 }228 }229 return lastMissed, sched.Next(now), nil230 }231 // +kubebuilder:docs-gen:collapse=getNextSchedule232 // figure out the next times that we need to create233 // jobs at (or anything we missed).234 missedRun, nextRun, err := getNextSchedule(&cronJob, r.Now())235 if err != nil {236 log.Error(err, "unable to figure out CronJob schedule")237 // we don't really care about requeuing until we get an update that238 // fixes the schedule, so don't return an error239 return ctrl.Result{}, nil240 }241 // Prep our eventual request to requeue until the next job242 scheduledResult := ctrl.Result{RequeueAfter: nextRun.Sub(r.Now())} // save this so we can re-use it elsewhere243 log = log.WithValues("now", r.Now(), "next run", nextRun)244 // Run a new job if it's on schedule245 if missedRun.IsZero() {246 log.V(1).Info("no upcoming scheduled times, sleeping until next")247 return scheduledResult, nil248 }249 // make sure we're not too late to start the run250 log = log.WithValues("current run", missedRun)251 tooLate := false252 if cronJob.Spec.StartingDeadlineSeconds != nil {253 tooLate = missedRun.Add(time.Duration(*cronJob.Spec.StartingDeadlineSeconds) * time.Second).Before(r.Now())254 }255 if tooLate {256 log.V(1).Info("missed starting deadline for last run, sleeping till next")257 // TODO(directxman12): events258 return scheduledResult, nil259 }260 // figure out how to run this job -- concurrency policy might forbid us from running261 // multiple at the same time...262 if cronJob.Spec.ConcurrencyPolicy == batchv1.ForbidConcurrent && len(activeJobs) > 0 {263 log.V(1).Info("concurrency policy blocks concurrent runs, skipping", "num active", len(activeJobs))264 return scheduledResult, nil265 }266 // ...or instruct us to replace existing ones...267 if cronJob.Spec.ConcurrencyPolicy == batchv1.ReplaceConcurrent {268 for _, activeJob := range activeJobs {269 // we don't care if the job was already deleted270 if err := r.Delete(ctx, activeJob, client.PropagationPolicy(metav1.DeletePropagationBackground)); client.IgnoreNotFound(err) != nil {271 log.Error(err, "unable to delete active job", "job", activeJob)272 return ctrl.Result{}, err273 }274 }275 }276 // construct a job based on our CronJob's template.277 constructJobForCronJob := func(cronJob *batchv1.CronJob, scheduledTime time.Time) (*kbatch.Job, error) {278 // We want job names for a given nominal start time to have a deterministic name to avoid the same job being created twice279 name := fmt.Sprintf("%s-%d", cronJob.Name, scheduledTime.Unix())280 job := &kbatch.Job{281 ObjectMeta: metav1.ObjectMeta{282 Labels: make(map[string]string),283 Annotations: make(map[string]string),284 Name: name,285 Namespace: cronJob.Namespace,286 },287 Spec: *cronJob.Spec.JobTemplate.Spec.DeepCopy(),288 }289 for k, v := range cronJob.Spec.JobTemplate.Annotations {290 job.Annotations[k] = v291 }292 job.Annotations[scheduledTimeAnnotation] = scheduledTime.Format(time.RFC3339)293 for k, v := range cronJob.Spec.JobTemplate.Labels {294 job.Labels[k] = v295 }296 if err := ctrl.SetControllerReference(cronJob, job, r.Scheme); err != nil {297 return nil, err298 }299 return job, nil300 }301 // +kubebuilder:docs-gen:collapse=constructJobForCronJob302 // actually make the job...303 job, err := constructJobForCronJob(&cronJob, missedRun)304 if err != nil {305 log.Error(err, "unable to construct job from template")306 // don't bother requeuing until we get a change to the spec307 return scheduledResult, nil308 }309 // ...and create it on the cluster310 if err := r.Create(ctx, job); err != nil {311 log.Error(err, "unable to create Job for CronJob", "job", job)312 return ctrl.Result{}, err313 }314 log.V(1).Info("created Job for CronJob run", "job", job)315 // Requeue when we either see a running job316 return scheduledResult, nil317}318var (319 jobOwnerKey = ".metadata.controller"320 apiGVStr = batchv1.GroupVersion.String()321)322func (r *CronJobReconciler) SetupWithManager(mgr ctrl.Manager) error {323 // set up a real clock, since we're not in a test324 if r.Clock == nil {325 r.Clock = realClock{}326 }327 if err := mgr.GetFieldIndexer().IndexField(context.Background(), &kbatch.Job{}, jobOwnerKey, func(rawObj client.Object) []string {328 // grab the job object, extract the owner...329 job := rawObj.(*kbatch.Job)330 owner := metav1.GetControllerOf(job)331 if owner == nil {332 return nil333 }334 // ...make sure it's a CronJob...335 if owner.APIVersion != apiGVStr || owner.Kind != "CronJob" {336 return nil337 }338 // ...and if so, return it339 return []string{owner.Name}340 }); err != nil {341 return err342 }343 return ctrl.NewControllerManagedBy(mgr).344 For(&batchv1.CronJob{})....

Full Screen

Full Screen

cronjob.go

Source:cronjob.go Github

copy

Full Screen

...18 watch "k8s.io/apimachinery/pkg/watch"19 scheme "k8s.io/client-go/kubernetes/scheme"20 rest "k8s.io/client-go/rest"21)22// CronJobsGetter has a method to return a CronJobInterface.23// A group's client should implement this interface.24type CronJobsGetter interface {25 CronJobs(namespace string) CronJobInterface26}27// CronJobInterface has methods to work with CronJob resources.28type CronJobInterface interface {29 Create(*v2alpha1.CronJob) (*v2alpha1.CronJob, error)30 Update(*v2alpha1.CronJob) (*v2alpha1.CronJob, error)31 UpdateStatus(*v2alpha1.CronJob) (*v2alpha1.CronJob, error)32 Delete(name string, options *v1.DeleteOptions) error33 DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error34 Get(name string, options v1.GetOptions) (*v2alpha1.CronJob, error)35 List(opts v1.ListOptions) (*v2alpha1.CronJobList, error)36 Watch(opts v1.ListOptions) (watch.Interface, error)37 Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v2alpha1.CronJob, err error)38 CronJobExpansion39}40// cronJobs implements CronJobInterface41type cronJobs struct {42 client rest.Interface43 ns string44}45// newCronJobs returns a CronJobs46func newCronJobs(c *BatchV2alpha1Client, namespace string) *cronJobs {47 return &cronJobs{48 client: c.RESTClient(),49 ns: namespace,50 }51}52// Get takes name of the cronJob, and returns the corresponding cronJob object, and an error if there is any.53func (c *cronJobs) Get(name string, options v1.GetOptions) (result *v2alpha1.CronJob, err error) {54 result = &v2alpha1.CronJob{}55 err = c.client.Get().56 Namespace(c.ns).57 Resource("cronjobs").58 Name(name).59 VersionedParams(&options, scheme.ParameterCodec).60 Do().61 Into(result)62 return63}64// List takes label and field selectors, and returns the list of CronJobs that match those selectors.65func (c *cronJobs) List(opts v1.ListOptions) (result *v2alpha1.CronJobList, err error) {66 result = &v2alpha1.CronJobList{}67 err = c.client.Get().68 Namespace(c.ns).69 Resource("cronjobs").70 VersionedParams(&opts, scheme.ParameterCodec).71 Do().72 Into(result)73 return74}75// Watch returns a watch.Interface that watches the requested cronJobs.76func (c *cronJobs) Watch(opts v1.ListOptions) (watch.Interface, error) {77 opts.Watch = true78 return c.client.Get().79 Namespace(c.ns).80 Resource("cronjobs").81 VersionedParams(&opts, scheme.ParameterCodec).82 Watch()83}84// Create takes the representation of a cronJob and creates it. Returns the server's representation of the cronJob, and an error, if there is any.85func (c *cronJobs) Create(cronJob *v2alpha1.CronJob) (result *v2alpha1.CronJob, err error) {86 result = &v2alpha1.CronJob{}87 err = c.client.Post().88 Namespace(c.ns).89 Resource("cronjobs").90 Body(cronJob).91 Do().92 Into(result)...

Full Screen

Full Screen

Get

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 c := cron.New()4 c.AddFunc("*/1 * * * *", func() { fmt.Println("Every 1 minute") })5 c.AddFunc("*/2 * * * *", func() { fmt.Println("Every 2 minute") })6 c.AddFunc("*/3 * * * *", func() { fmt.Println("Every 3 minute") })7 c.AddFunc("*/4 * * * *", func() { fmt.P

Full Screen

Full Screen

Get

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 c := cron.New()4 c.AddFunc("* * * * *", func() { fmt.Println("Every minute on the minute") })5 c.AddFunc("*/5 * * * *", func() { fmt.Println("Every 5 minutes") })6 c.AddFunc("0 */5 * * *", func() { fmt.Println("Every 5 minutes on the hour") })7 c.AddFunc("0 0 1 * *", func() { fmt.Println("Every day

Full Screen

Full Screen

Get

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 c := cron.New()4 c.AddFunc("* * * * *", func() { fmt.Println("Every minute on the minute") })5 c.Start()6 select {}7}8import (9func main() {10 c := cron.New()11 c.AddFunc("* * * * *", func() { fmt.Println("Every minute on the minute") })12 c.Start()13 select {}14}15import (16func main() {17 c := cron.New()18 c.AddFunc("* * * * *", func() { fmt.Println("Every minute on the minute") })19 c.Start()20 select {}21}22import (23func main() {24 c := cron.New()25 c.AddFunc("* * * * *", func() { fmt.Println("Every minute on the minute") })26 c.Start()27 select {}28}29import (30func main() {31 c := cron.New()32 c.AddFunc("* * * * *", func() { fmt.Println("Every minute on the minute") })33 c.Start()34 select {}35}36import (37func main() {38 c := cron.New()39 c.AddFunc("* * * * *", func() { fmt.Println("Every minute on the minute") })40 c.Start()41 select {}42}43import (44func main() {

Full Screen

Full Screen

Get

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 c := cron.New()4 c.AddFunc("0 30 11 * * *", func() { fmt.Println("Every day at 11:30am") })5 c.AddFunc("@hourly", func() { fmt.Println("Every hour") })6 c.AddFunc("@every 1h30m", func() { fmt.Println("Every hour thirty") })7 c.Start()8}

Full Screen

Full Screen

Get

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 c := cron.New()4 c.AddFunc("* * * * *", func() { fmt.Println("Every second") })5 c.AddFunc("@hourly", func() { fmt.Println("Every hour") })6 c.AddFunc("@every 1h30m", func() { fmt.Println("Every hour thirty") })7 c.Start()8 time.Sleep(5 * time.Minute)

Full Screen

Full Screen

Get

Using AI Code Generation

copy

Full Screen

1import ( 2func main() {3 c := cron.New()4 c.AddFunc("*/1 * * * *", func() { fmt.Println("Every hour on the half hour") })5 c.Start()6 select {}7}

Full Screen

Full Screen

Get

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 c := cron.New()4 c.AddFunc("0 0 12 * * ?", func() { fmt.Println("Every day at noon") })5 c.AddFunc("@hourly", func() { fmt.Println("Every hour") })6 c.AddFunc("@every 1h30m", func() { fmt.Println("Every hour thirty") })7 c.Start()8 time.Sleep(10 * time.Second)9 c.Stop()10}

Full Screen

Full Screen

Get

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 cronjob.Get()4 fmt.Println(cronjob)5}6{0xc0000b0000 0xc0000b4000}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Testkube automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful