eixcs
eixcs

Reputation: 1989

@Scheduled and websocket, message not reaching the Angular client

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);
}

Upvotes: 0

Views: 157

Answers (2)

Ananthapadmanabhan
Ananthapadmanabhan

Reputation: 6216

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);
    }
}

Upvotes: 1

eixcs
eixcs

Reputation: 1989

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 :)

Upvotes: 0

Related Questions