0

I'm having trouble sending websocket messages to the client using a @Scheduled task. I've added the code below. Every minute I'm checking if I have any jobs that should start automatically and if there is any, I start them and send a websocket message so the client knows the job has started.

Right now everything else apart from the websocket part works. The client just doesn't get the message, but I know it's working because I use the same updateLogisticClients method elsewhere too and it works 100% of the time.

I am thinking it's because of @Scheduled because it works for regular methods... Any ideas?

@Transactional
@Scheduled(cron = "0 * * * * *")
public List<DayJob> startRentJobsAutomatically() {
    List<DayJob> dayJobsToStart = getRentJobsToStart();
    for (DayJob dayJob : dayJobsToStart) {
        dayJob.setActualStartTime(dayJob.getStartTime());
        dayJob.setStatus(DayJob.DayJobStatus.in_progress);
        DayJobDetailResponse response = new DayJobDetailResponse(dayJobRepository.save(dayJob));
        updateLogisticClients(response);
    }
    return dayJobsToStart;
}

@SendTo("/logistic-data/day")
public void updateLogisticClients(DayJobDetailResponse response) {
    System.out.println("SENT");
    webSocket.convertAndSend("/logistic-data/day/" + CompanyContext.getCurrentCompanyId(), response);
}

2 Answers 2

1

Just calling the web socket endpoint from a scheduled one won't trigger it for you. Use a separate scheduled component like :

@Component
public class ScheduledUpdatesOnTopic{

    @Autowired
    private SimpMessagingTemplate template;

    @Scheduled(fixedDelay=300)
    public void publishUpdates(){
      List<DayJob> dayJobsToStart = getRentJobsToStart();
      for (DayJob dayJob : dayJobsToStart) {
        dayJob.setActualStartTime(dayJob.getStartTime());
        dayJob.setStatus(DayJob.DayJobStatus.in_progress);
        DayJobDetailResponse response = new DayJobDetailResponse(dayJobRepository.save(dayJ
        template.convertAndSend("/logistic-data/day", response);
    }
}
1
  • Turned out to be another problem, thanks for the help though :)
    – eixcs
    Aug 21, 2020 at 6:58
0

Turns out CompanyContext.getCurrentCompanyId() returns null and the client listens for specific company I depending on the user. I have seperate company data in the database that gets accessed via companyId and if it's a @Scheduled task, the companyId is not set :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.