Generating a report in a background task

Report generation may involve expensive computation due to large amounts of data, connections to external systems, and data processing. In many situations, report data is gathered directly from the original source, typically an SQL database. This has two clear drawbacks. The first problem is that as the application runs, more and more data is added into the database, making reports run slower with time. The second problem is that report generation may heavily use the database at certain times, interfering with the usage of other parts of the application.

One step toward improving this situation is to progressively and continuously generate the data required for reporting. For example, consider the following query that calculates the average on a column:

SELECT AVG(column_name) FROM table_name

Instead of using this query, you can use the following formula to continuously calculate the average (an) from the previous average value (an-1) every time a new value (xn) is persisted:

This, of course, doesn't take into account delete operations, and requires calculating the average any time a new value is persisted in the database, but the key idea of this simple example is to try to help the application to pre-generate data for reporting, as data is added, modified, or deleted in order to minimize the amount of computational power required at report generation time.

When pre-processing data, or when there are computations that depend on time or external data sources, report generation may take longer than a normal request to the application. In these cases, you can use background threads to generate the report and notify the user when the report is ready. In the example application, you can see an Annual legal report option in the Reports menu. Generating this report is expensive in terms of application time, so instead of locking the application's usage until the report is ready, the application shows a notification saying that the report is being generated and starts the process in a background thread, letting users visualize other reports in the meantime:

When the report is ready, the application notifies you again and shows a button that allows you to download the report:

The next sections explain how to implement this behavior.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset